What is Record in C#: Definition and Usage
record in C# is a special type that provides built-in support for immutable data and value-based equality. It is designed to represent simple data objects with less code and automatic features like ToString(), Equals(), and GetHashCode().How It Works
A record in C# works like a class but is optimized for storing data. Imagine a record as a simple container for information, like a form you fill out once and then keep unchanged. Unlike regular classes, records automatically compare their contents instead of their memory addresses, so two records with the same data are considered equal.
Records are immutable by default, meaning once you create a record, you cannot change its data. This is like writing your details on a card and sealing it; you can read it anytime, but you cannot alter it. This immutability helps avoid bugs and makes your code easier to understand.
Example
public record Person(string FirstName, string LastName); class Program { static void Main() { var person1 = new Person("Alice", "Smith"); var person2 = new Person("Alice", "Smith"); System.Console.WriteLine(person1); // Prints the data nicely System.Console.WriteLine(person1 == person2); // True because data is equal } }
When to Use
Use records when you need to represent simple data objects that should not change after creation. They are perfect for data transfer objects, configuration settings, or any case where you want to compare objects by their content, not by their identity.
For example, if you are building an app that handles user profiles or product details, records let you write less code and avoid mistakes related to changing data accidentally.
Key Points
- Records provide built-in immutability and value-based equality.
- They reduce boilerplate code by auto-generating methods like
ToString()andEquals(). - Records are ideal for simple data containers and data transfer objects.
- You can create mutable records, but immutability is the default and recommended.