0
0
CsharpConceptBeginner · 3 min read

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

This example shows how to define and use a record in C#. It creates two records with the same data and compares them.
csharp
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
    }
}
Output
Person { FirstName = Alice, LastName = Smith } True
🎯

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() and Equals().
  • Records are ideal for simple data containers and data transfer objects.
  • You can create mutable records, but immutability is the default and recommended.

Key Takeaways

Records in C# are designed for immutable data with value-based equality.
They automatically generate useful methods, reducing the need for extra code.
Use records for simple data objects that should not change after creation.
Records help make your code clearer and less error-prone by focusing on data content.