csharp / intermediate
Snippet
Immutability with C# Records
Records are reference types that provide built-in functionality for encapsulating data. They use value-based equality and support non-destructive mutation via the 'with' expression.
snippet.csharp
1
2
3
4
public record Product(string Id, string Name, decimal Price);var original = new Product("A1", "Laptop", 999.99m);var discount = original with { Price = 899.99m };
Breakdown
1
public record Product(...);
Defines a positional record with properties that are immutable by default.
2
original with { Price = 899.99m }
Creates a new instance of the record with one or more modified properties.