Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-9.0

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?

like image 840
Danila Kireev Avatar asked Jan 31 '26 05:01

Danila Kireev


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

like image 140
Roman Marusyk Avatar answered Feb 02 '26 18:02

Roman Marusyk


this syntax about record in c# 9.0 and this is Immutable type indeed all immutable types are creating new object like as struct for more information about this you can see this https://channel9.msdn.com/Shows/On-NET/C-9-Language-Features

like image 34
Alireza heidari Avatar answered Feb 02 '26 17:02

Alireza heidari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!