DEV Community

Cover image for C# - Use Record Types for Immutable Data Structures
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Use Record Types for Immutable Data Structures

In C#, you can use record types to define immutable data structures. Records are a concise syntax to create an immutable object with value equality. Unlike classes, records provide a built-in copy-and-update functionality which can be very useful for functional-style programming patterns.

Here's a quick example of how you might use a record type:

public record Person(string FirstName, string LastName, int Age);

public static void Main(string[] args)
{
    var originalPerson = new Person("Jane", "Doe", 30);

    // Create a new record instance with the Age updated, keeping the rest of the fields the same.
    var updatedPerson = originalPerson with { Age = 31 };

    Console.WriteLine(originalPerson); // Output: Person { FirstName = Jane, LastName = Doe, Age = 30 }
    Console.WriteLine(updatedPerson); // Output: Person { FirstName = Jane, LastName = Doe, Age = 31 }
}
Enter fullscreen mode Exit fullscreen mode

This shows the simplicity of creating and manipulating immutable objects using records, which can help you manage state more predictably in your applications. Use records when you need value-based equality and immutability for more robust and maintainable code.

Top comments (0)