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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay