C# ยท Chapter 40 of 46

C# Records

A record is a special type introduced in C# 9 designed for immutable data models. Records automatically provide value-based equality, meaning two records with the same data are considered equal, unlike classes which compare by reference.

Records are ideal for representing data that shouldn't change after creation, like a data transfer object (DTO) or a configuration snapshot.

Syntax
record Name(type Prop1, type Prop2);

Defining records

A record can be declared concisely using positional syntax, like `record Person(string Name, int Age);`, which automatically generates properties, a constructor, and equality comparison.

Value equality and immutability

Two record instances with identical property values are considered equal using ==, unlike classes. Records also support 'with' expressions to create a modified copy without changing the original.

Example 1 (csharp)
using System;

record Person(string Name, int Age);

class Program {
  static void Main() {
    Person p1 = new Person("Amy", 25);
    Person p2 = new Person("Amy", 25);
    Console.WriteLine(p1 == p2);
  }
}
Output
True

Records compare by value, so two records with the same data are considered equal.

Example 2 (csharp)
using System;

record Person(string Name, int Age);

class Program {
  static void Main() {
    Person p1 = new Person("Amy", 25);
    Person p2 = p1 with { Age = 26 };
    Console.WriteLine(p1.Age + " " + p2.Age);
  }
}
Output
25 26

The with expression creates a new record copy with one property changed, leaving the original unchanged.

Key points

  • Records provide built-in value-based equality.
  • Positional records auto-generate properties and a constructor.
  • The `with` expression creates a modified copy of a record.
  • Records are ideal for immutable data models.
๐Ÿ’ก Note: Records can also be declared with class-like syntax and mutable properties if needed, but immutability is the common default use case.

๐Ÿ“ Quick Quiz

1. How do records compare for equality by default?

2. What does the `with` expression do?

3. What C# version introduced records?