Monday, January 25, 2021

C# 9.0: Record Types Non-Destructive Mutation (the With expression)

A C# 9.0 record type is immutable but there are times when it is useful to make a copy of a record type but only modify a subset of the properties. Under this scenario, the with express can be used with facilitates non-destructive mutation. To quote Steve Fenton's blog (C# 9 Non-Destructive Mutation): 


To demonstrate non-destructive mutation consider the following record type, a positional record (see C# 9.0: Positional Records):

public record Employee (
                  string Name, 
                  string Department,
                  string Office)
{
}    

The code below uses the with expression to make a copy of a record but allows specific properties to be changed in the newly created record and obviously does not modify the original record:


In the coding sample above, the first Employee record created is assigned to variable, victoria (line 13). The above code utilizes with expressions and behaves as follows:
  • Line 14: the victoria record instance is used to create a new employee, mario, but assigns a new value to the Name property, Mario Aguayo,
  • Line 15: the victoria record instance  is used to create a new employee, tarun, but assigns a new value to the Name property, Tarun Tiwari.
  • Line 16: the victoria record instance  is used to create a new employee, kai, but assigns a new value to the Name property, Kai Feng and Department property, QA.
  • Line 17: the kai record instance is used to create  a new employee, daisuke, but assigns a new value to the Name property, Daisuke Katchi and Office property, Via Carmen Suites.
 

No comments :

Post a Comment