Posts

Showing posts from May, 2026

C# Records

Introduction C# records and record structs  are relatively new. Records offer some advantages over regular classes and structs, which I will cover here, but they are essentially another way to declare them. This is another back to basics article. We essentially use records for: Entities, such as the ones we would store in a database Value objects/ Data Transfer Objects Immutable classes Let's now see how to work with them. Syntax Records are declared like this: public record Point(int X, int Y); Or like this, with the exact same meaning: public record Point { public int X { get; init; } public int Y { get; init; } } And we instantiate a record just like any other class or struct: Point p1 = new(1, 2); //or var p1 = new Point(1, 2); We can, of course, use  positional or named arguments : var p1 = new Point(Y: 2, X: 1); It is possible to add new properties (or methods) besides the ones declared on the primary constructor , we don't need to live with just those pro...