๐ŸŽ“ A1Learner
๐Ÿ”
0 of 38 lessons completed

C# Records

A record is a class-like type built for holding data. Records compare by their values, not by their identity.

A positional record

One line declares the record and its two properties. Printing it shows the generated text form.

using System;

record Person(string Name, int Age);

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person("Hana", 27);
        Console.WriteLine(person);
    }
}

Records compare by value

Two separate records with the same values are equal. A record with a different age is not equal.

using System;

record Person(string Name, int Age);

class Program
{
    static void Main(string[] args)
    {
        Person first = new Person("Hana", 27);
        Person second = new Person("Hana", 27);
        Person third = new Person("Hana", 28);
        Console.WriteLine("First equals second: " + (first == second));
        Console.WriteLine("First equals third: " + (first == third));
    }
}

Copying with the with expression

The with expression builds a changed copy. The original record keeps its old value.

using System;

record Person(string Name, int Age);

class Program
{
    static void Main(string[] args)
    {
        Person first = new Person("Hana", 27);
        Person older = first with { Age = 28 };
        Console.WriteLine(older);
        Console.WriteLine("First age still: " + first.Age);
    }
}

Example

using System;

record Song(string Title, int Seconds);

class Program
{
    static void Main(string[] args)
    {
        Song song = new Song("River", 180);
        Song longer = song with { Seconds = 200 };
        Console.WriteLine(song);
        Console.WriteLine(longer);
        Console.WriteLine("Same title: " + (song.Title == longer.Title));
    }
}

Key points

  • A positional record lists its properties inside parentheses after the name.
  • The compiler writes the properties, the constructor, and a readable print form.
  • Two records with equal values compare as equal with ==.
  • A class with the same values would compare by reference instead.
  • The with expression copies a record and changes the listed properties.
  • The original record stays unchanged after a with copy.

In this example, a Song record holds a title and a length in seconds. The with expression copies it with a new length. The first print line shows the original record unchanged. The last line confirms both copies share the same title.

Note

Records suit data that is read more often than it is changed.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does the expression `first with { Age = 28 }` produce?