An utra-compact way to create structs or classes whose primary role is storing data.
The record modifier instructs the compiler to synthesize members that are
useful for types whose primary role is storing data. This includes an overload
of ToString() and members which support value equality.
public record Person(string FirstName, string LastName);
public static class Program
{
public static void Main()
{
Person person = new("Nancy", "Davolio");
Console.WriteLine(person);
// output: Person { FirstName = Nancy, LastName = Davolio }
}
}
immutable by default
When you define a record it starts with properties and a matching constructor.
These properties will have get and init making them immutable after being
created.
stringify
Records automatically override the ToString method with a convenient printable representation of the data.
value semantics
Records, even those backed by a class, automatically have value semantics instead of reference semantics. Basically, that means you can do an equality check (the Equals method is overridded) and you will get the result you want even if they're occupying different locations in memory:
public record Point(float X, float Y);
Point a = new Point(2, 3);
Point b = new Point(2, 3);
Console.WriteLine(a == b); // True
deconstruction
Much like a tuple you can deconstruct a record:
Point p = new Point(-2, 6);
(float x, float y) = p;
with statement
Given that records are immutable by default, it's common to want to make a copy with a slight change:
Point a = new Point(-2, 4);
Point b = a with { X = 0 };
struct based records
By default the compiler turns records into classes, but you can back them with a struct instead:
public record struct Point(float X, float Y);