0
0
C Sharp (C#)programming~5 mins

With expressions for immutable copies in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a 'with expression' in C#?
A 'with expression' creates a new object by copying an existing immutable object and changing some of its properties without modifying the original.
Click to reveal answer
beginner
How do 'with expressions' help with immutability?
They allow you to create modified copies of objects without changing the original, preserving immutability and avoiding side effects.
Click to reveal answer
beginner
Given a record:
record Person(string Name, int Age);
How do you create a copy with a new Age using a with expression?
var olderPerson = person with { Age = person.Age + 1 };
This creates a new Person with the same Name but Age increased by 1.
Click to reveal answer
intermediate
Can 'with expressions' be used with classes that are not records?
No, 'with expressions' work primarily with records or types that support them. Regular classes need custom cloning methods.
Click to reveal answer
intermediate
What happens if you use a with expression but don't change any properties?
A new object is still created, but it has the same property values as the original, effectively a shallow copy.
Click to reveal answer
What does the 'with' keyword do in C# records?
AConverts a record to a class
BModifies the original record in place
CDeletes the record
DCreates a new record by copying and modifying specified properties
Which of these is true about 'with expressions'?
AThey create a new object with some changed properties
BThey are used to delete properties
CThey only work with mutable classes
DThey mutate the original object
Given
record Point(int X, int Y);
How to create a new Point with X=5 but same Y as p?
ABoth B and C
Bvar p2 = new Point(5, p.Y);
Cvar p2 = p with { X = 5 };
DNone of the above
Can you use 'with expressions' to change nested objects inside a record?
AYes, directly and deeply
BNo, only top-level properties can be changed
CYes, but only if nested objects are mutable
DNo, 'with' only works on classes
What C# feature introduced 'with expressions' for immutable copies?
AC# 7.0
BC# 8.0
CC# 9.0
DC# 10.0
Explain how 'with expressions' help maintain immutability in C# records.
Think about how you can change data without changing the original object.
You got /3 concepts.
    Describe the difference between using a 'with expression' and modifying an object directly.
    Consider what happens to the original object in each case.
    You got /3 concepts.