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.
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.
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);
}
}TrueRecords compare by value, so two records with the same data are considered equal.
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);
}
}25 26The 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.
