Records are perfect for DTOs, value objects, and domain events where immutability and equality matter.
// Positional record — compiler generates constructor, Deconstruct, Equals, GetHashCode, ToString
public record Point(double X, double Y);
// Usage
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b); // True — value equality, not reference
Console.WriteLine(a); // Point { X = 1, Y = 2 }
// Non-destructive mutation
var c = a with { Y = 99 };
Console.WriteLine(c); // Point { X = 1, Y = 99 }
Console.WriteLine(a); // Point { X = 1, Y = 2 } — unchanged
// Record with extra members
public record Order(int Id, decimal Total, string Region)
{
// Computed property
public bool IsLargeOrder => Total > 1000;
// Validation in compact constructor
public Order
{
ArgumentOutOfRangeException.ThrowIfNegative(Total);
}
}
// Deconstruction
var (id, total, region) = new Order(42, 250m, "EU");
All Comments