C# records provide a concise way to create immutable reference types with built-in value-based equality.
// Immutable record with init-only properties
public record Person(string Name, int Age)
{
// Supports non-destructive mutation
public Person WithName(string newName) => this with { Name = newName };
}
// Usage
var person1 = new Person("Alice", 30);
var person2 = person1 with { Age = 31 }; // Creates a new instance
Key features:
Immutable by default
Value-based equality
Supports pattern matching
Simplified clone/copy with with
expression
Future topics will cover DateTime, EF Core, SQL, and other advanced .NET concepts.
Simplified clone/copy with with expression
a deep clone or not?No, the with
expression performs a shallow clone. It creates a new instance and copies reference type properties by reference, not creating deep copies.
Example to illustrate:
public record ComplexPerson(string Name, List<string> Hobbies);
var original = new ComplexPerson("Alice", new List<string> { "Reading" });
var clone = original with { Name = "Bob" };
// Modifying hobbies in clone will also affect original
clone.Hobbies.Add("Coding");
Console.WriteLine(original.Hobbies.Count); // Still 2, not isolated
For deep cloning, you'll need to manually implement deep copy logic or use serialisation techniques.
Records with with
expressions are primarily useful in scenarios requiring:
Immutable Domain Models
Create new object instances with slight variations
Maintain thread-safety
Support functional programming patterns
public record Order(int Id, decimal Total, DateTime CreatedAt);
// Easy to create modified versions without mutation
var updatedOrder = originalOrder with { Total = 150.00m };
Value Objects in Domain-Driven Design
Represent complex value types
Ensure objects are compared by value, not reference
Creating Configuration Variations
Easily generate new configurations with minimal changes
Useful in testing and configuration management
Practical in scenarios valuing immutability, functional programming, and clean object creation patterns.