?? Update in C# 12: Enhancements to with Expressions! ??
C# 12 brings a fantastic improvement to with expressions, making it even easier to work with immutable record types. This feature allows developers to create modified copies of records with minimal boilerplate, enhancing code clarity and maintainability.
What Are with Expressions?
With with expressions, you can create a new instance of a record by copying properties from an existing instance and changing only the specified ones. Here’s a quick example:
public record Person(string Name, int Age);
var person1 = new Person("Alice", 30);
var person2 = person1 with { Age = 31 };
Console.WriteLine($"Person 1: {person1.Name}, Age: {person1.Age}"); // Alice, 30
Console.WriteLine($"Person 2: {person2.Name}, Age: {person2.Age}"); // Alice, 31
These enhancements empower developers to write more efficient and maintainable code while embracing immutability.