Exploring Record Types in C# 9 and Beyond
C# 9 introduced record types, a powerful feature for creating immutable reference types with value-based equality. Let’s explore why and when to use them.
What are Records?
Records are reference types that provide built-in functionality for encapsulating data. They’re perfect for DTOs, value objects, and immutable data structures.
public record Person(string FirstName, string LastName, int Age);
This simple declaration gives you:
- Immutability by default
- Value-based equality
- Built-in ToString() override
- Deconstruction support
Value-Based Equality
Unlike classes, records compare by value:
var person1 = new Person("John", "Doe", 30);
var person2 = new Person("John", "Doe", 30);
Console.WriteLine(person1 == person2); // True!
Non-Destructive Mutation
Use the with expression to create modified copies:
var person = new Person("John", "Doe", 30);
var olderPerson = person with { Age = 31 };
Records vs Classes
Use records when:
- You need value-based equality
- Your type is primarily for holding data
- You want immutability
Use classes when:
- You need identity-based equality
- You have complex behavior
- Mutability is required
Record Structs (C# 10)
C# 10 added record structs for value type records:
public record struct Point(int X, int Y);
Records are a game-changer for writing clean, concise data models. Start using them in your next project!
