C# record types are designed to be immutable by default. When using a C# record type, you can create a new instance based on an existing instance using the with
expression.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var character = new Character | |
{ | |
FirstName = "Bart", | |
LastName = "Simpson" | |
}; | |
var newCharacter = character with { FirstName = "Homer" }; |
Behind the scenes the compiler will generate a Clone method that calls a copy constructor:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class Character | |
{ | |
// ... | |
[CompilerGenerated] | |
public virtual Character <Clone>$() | |
{ | |
return new Character(this); | |
} | |
[CompilerGenerated] | |
protected Character(Character original) | |
{ | |
<FirstName>k__BackingField = original.<FirstName>k__BackingField; | |
<LastName>k__BackingField = original.<LastName>k__BackingField; | |
} | |
} |
Although a default copy constructor is generated for you, you can create your own if you want to:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public record Character(string FirstName, string LastName) | |
{ | |
protected Character(Character other) | |
{ | |
FirstName = other.FirstName; | |
LastName = other.LastName; | |
// Do something else | |
} | |
} |