Records in C#
Value semantics in one line: printing, equality and copies with a change.
var current = new Semver(2, 1);
var next = current with { Minor = 2 };
Console.WriteLine(current); // records print themselves
Console.WriteLine(next);
Console.WriteLine(current == new Semver(2, 1)); // and compare by value
record Semver(int Major, int Minor)
{
public override string ToString() => $"v{Major}.{Minor}";
}
How it works
record Semver(int Major, int Minor)declares the whole type.withcopies the record, changing only what you name.- Records with equal values are equal; classes would compare references.
Keywords and builtins used here
SemverToStringintnewoverridepublicrecordstringvarwith
The run, in numbers
- Lines
- 11
- Characters to type
- 343
- Tokens
- 73
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 52 seconds.
Step 4 of 4 in Classes & records, step 21 of 29 in Language basics.