Practice mode C#

What does the with expression do on a C# record, as in var p2 = p1 with { Y = 5 };?

Correct answer B. Creates a copy of p1 with Y changed to 5, leaving p1 unchanged

Explanation

The with expression performs non-destructive mutation. It clones the record and then applies the listed property assignments to the copy, so p1 keeps its original Y and p2 has Y equal to 5. This fits records whose positional properties are init-only. Since C# 10, with also works on structs and anonymous types.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.