typestar

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

  1. record Semver(int Major, int Minor) declares the whole type.
  2. with copies the record, changing only what you name.
  3. Records with equal values are equal; classes would compare references.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Classes & records, step 21 of 29 in Language basics.

← Previous Next →

Records in other languages