C# 9.0 With-expressions. How to use them?

Viewed 321

The new C# 9.0 syntax allows for a new kind of expression:

var newPerson = oldPerson with { Age = "21" };

Following questions arise when looking at the previous code line:

  1. Is it a reference or a new object copy?
  2. If it's a reference, what about the inheritance? Consider the following code line:
Person child = new Child{ FirstName = "Jan", LastName = "Brown", IsInKindergarten = false };
Person person = child with { LastName = "Williams" }

Does the compiler allow the person object to inherit the IsInKindergarten property?

2 Answers

In this case var newPerson = oldPerson with { Age = "21" }; it creates a new object that’s a copy of the old one, except with a different age.

Does the compiler allow the person object to inherit the IsInKindergarten property?

yes, the person will be FirstName = "Jan", LastName = "Williams", IsInKindergarten = false

Related