One of the most anticipated features coming in C#9 are Record types. Record types make it easy to create immutable reference types in .NET. They become the perfect fit for Value Objects in DDD terms.
A new keyword is introduced to support this: record. The record keyword makes an object immutable and behave like a value type.
An example:
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 Person | |
{ | |
public string LastName { get; } | |
public string FirstName { get; } | |
public Person(string first, string last) => (FirstName, LastName) = (first, last); | |
} |
You can even write this using a shorter syntax using positional records:
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 Person(string FirstName, string LastName); |
But what if you want to change the person name? How can we do this knowing that the object is immutable? Do I need to copy all properties into a new object?
Letās introduce the with keyword to fix this. It allows you create an object from another by specifying what property changes:
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 person = new Person("Bill", "Wagner"); | |
var anotherPerson = person with { LastName = "Gates" }; |