Bird
Raised Fist0
C Sharp (C#)programming~10 mins

With expressions for immutable copies in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - With expressions for immutable copies
Create original record
↓
Use 'with' expression
↓
Copy original with changes
↓
New record created, original unchanged
↓
Use new record as needed
Start with an original record, use 'with' to make a copy with some changes, resulting in a new record while the original stays the same.
Execution Sample
C Sharp (C#)
record Person(string Name, int Age);

var p1 = new Person("Alice", 30);
var p2 = p1 with { Age = 31 };

Console.WriteLine(p1);
Console.WriteLine(p2);
Creates a Person record, then makes a copy with a changed Age using 'with' expression, printing both.
Execution Table
StepActionVariable ValuesOutput
1Create p1 with Name='Alice', Age=30p1 = Person(Name='Alice', Age=30)
2Create p2 as copy of p1 with Age=31p2 = Person(Name='Alice', Age=31)
3Print p1p1 unchangedPerson { Name = Alice, Age = 30 }
4Print p2p2 has Age=31Person { Name = Alice, Age = 31 }
5EndNo changes
💡 Execution ends after printing both records; original remains unchanged.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
p1undefinedPerson(Name='Alice', Age=30)Person(Name='Alice', Age=30)Person(Name='Alice', Age=30)
p2undefinedundefinedPerson(Name='Alice', Age=31)Person(Name='Alice', Age=31)
Key Moments - 2 Insights
Why does changing Age in p2 not affect p1?
Because 'with' creates a new copy with changes, leaving the original p1 unchanged, as shown in steps 2 and 3 of the execution_table.
Is p2 a reference to p1 or a new object?
p2 is a new object created by copying p1 and changing Age, not a reference to p1, as seen in variable_tracker after step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the Age value of p2?
A30
Bundefined
C31
D0
💡 Hint
Check the 'Variable Values' column at step 2 in execution_table.
At which step does p1 get created?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for creation of p1.
If we changed p1's Name after step 1, would p2's Name change?
ANo, because p2 is a copy made before the change
BYes, because records are mutable
CYes, because p2 references p1
DNo, because p2 is unrelated
💡 Hint
Refer to variable_tracker and key_moments about immutability and copying.
Concept Snapshot
With expressions create a new immutable copy of a record with some changes.
Syntax: var newRecord = oldRecord with { Property = newValue };
Original record stays unchanged.
Useful for immutable data updates.
Works only with records or types supporting 'with'.
Full Transcript
This example shows how to use 'with' expressions in C# to create immutable copies of records. First, we create a record p1 with Name 'Alice' and Age 30. Then, using 'with', we create p2 as a copy of p1 but with Age changed to 31. Printing p1 and p2 shows that p1 remains unchanged while p2 has the updated Age. This demonstrates that 'with' expressions produce new objects without modifying the original, supporting safe immutable data handling.

Practice

(1/5)
1. What does the with expression do in C# when used with records?
easy
A. Creates a new record by copying an existing one and changing specified properties
B. Modifies the original record directly
C. Deletes the original record and creates a new one
D. Copies the record without allowing any changes

Solution

  1. Step 1: Understand the purpose of with expression

    The with expression is designed to create a new object by copying an existing one but allows changing some properties.
  2. Step 2: Compare behavior with original object

    The original object remains unchanged; only the new object has the updated properties.
  3. Final Answer:

    Creates a new record by copying an existing one and changing specified properties -> Option A
  4. Quick Check:

    With expression = new copy with changes [OK]
Hint: Remember: with creates a new object, original stays same [OK]
Common Mistakes:
  • Thinking with modifies the original object
  • Assuming with deletes the original object
  • Believing with copies without allowing changes
2. Which of the following is the correct syntax to create a new record person2 from person1 with a changed Age property using a with expression?
easy
A. var person2 = person1.Age = 30 with;
B. var person2 = with person1 { Age = 30 };
C. var person2 = person1 { with Age = 30 };
D. var person2 = person1 with { Age = 30 };

Solution

  1. Step 1: Recall the correct syntax for with expressions

    The correct syntax is: var newRecord = oldRecord with { Property = value };
  2. Step 2: Match the syntax with options

    var person2 = person1 with { Age = 30 }; matches the correct syntax exactly, others have misplaced keywords or incorrect order.
  3. Final Answer:

    var person2 = person1 with { Age = 30 }; -> Option D
  4. Quick Check:

    Correct syntax = var person2 = person1 with { Age = 30 }; [OK]
Hint: with comes after the variable, then braces with changes [OK]
Common Mistakes:
  • Placing 'with' before the variable
  • Using incorrect braces or order
  • Trying to assign property outside braces
3. Given the record declaration and code below, what is the output?
public record Person(string Name, int Age);

var person1 = new Person("Alice", 25);
var person2 = person1 with { Age = 30 };
Console.WriteLine(person1.Age);
Console.WriteLine(person2.Age);
medium
A. 25 25
B. 30 30
C. 25 30
D. 30 25

Solution

  1. Step 1: Understand the with expression effect on Age

    person2 is a new record copied from person1 but with Age changed to 30. person1 remains unchanged with Age 25.
  2. Step 2: Determine the printed values

    Printing person1.Age outputs 25, printing person2.Age outputs 30.
  3. Final Answer:

    25 30 -> Option C
  4. Quick Check:

    Original Age = 25, New Age = 30 [OK]
Hint: Original stays same, new copy has changed property [OK]
Common Mistakes:
  • Assuming original object changes
  • Mixing up which object's property is printed first
  • Expecting both to have same Age
4. Identify the error in the following code using with expressions:
public record Point(int X, int Y);

var p1 = new Point(5, 10);
var p2 = p1 with (X = 7);
medium
A. Using parentheses instead of braces in with expression
B. Cannot use with expression on records
C. Missing semicolon after record declaration
D. Cannot change properties in with expression

Solution

  1. Step 1: Check syntax of with expression

    The with expression requires braces { } around property assignments, not parentheses ( ).
  2. Step 2: Identify the error in code

    Code uses with (X = 7) which is invalid syntax; it should be with { X = 7 }.
  3. Final Answer:

    Using parentheses instead of braces in with expression -> Option A
  4. Quick Check:

    with uses braces, not parentheses [OK]
Hint: Use braces { } after with, not parentheses ( ) [OK]
Common Mistakes:
  • Using parentheses instead of braces
  • Thinking with can't change properties
  • Assuming with is not allowed on records
5. Consider the following records and code. What will be the output?
public record Address(string City, string Country);
public record Person(string Name, int Age, Address Address);

var addr1 = new Address("Paris", "France");
var person1 = new Person("Bob", 40, addr1);
var person2 = person1 with { Address = person1.Address with { City = "Lyon" } };

Console.WriteLine(person1.Address.City);
Console.WriteLine(person2.Address.City);
hard
A. Lyon Lyon
B. Paris Lyon
C. Paris Paris
D. Lyon Paris

Solution

  1. Step 1: Understand nested with expressions

    person2 is a new Person copied from person1, but its Address property is also copied and changed with a new City value "Lyon".
  2. Step 2: Determine original and new city values

    person1.Address.City remains "Paris" because original objects are immutable. person2.Address.City is "Lyon" due to the nested with expression.
  3. Final Answer:

    Paris Lyon -> Option B
  4. Quick Check:

    Nested with copies inner object with changes [OK]
Hint: Use nested with to copy and change inner objects immutably [OK]
Common Mistakes:
  • Assuming inner object changes original
  • Expecting both cities to be same
  • Not using nested with for inner property change
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard