C# > Functional Programming > Immutable Types > Creating Immutable Classes

Using `record` to Create Immutable Classes

This snippet demonstrates using the `record` type in C# 9 and later to create an immutable class. Records provide a concise syntax for creating immutable data structures with value-based equality.

Concepts Behind Records

Records are a special type in C# designed to simplify the creation of immutable data structures. They automatically generate value-based equality (based on the values of the properties), a `ToString()` method, and a copy constructor for creating new instances with modifications.

Record Implementation

This single line defines an immutable `PersonRecord` class. - `FirstName`, `LastName`, and `DateOfBirth` are properties. - The compiler automatically generates a constructor, equality members, a `ToString()` method, and a 'with' expression (copy constructor) for immutable updates.

public record PersonRecord(string FirstName, string LastName, DateTime DateOfBirth);

Usage Example

This shows how to create and use a `PersonRecord`. The `with` expression creates a new instance of the record based on an existing instance but with some properties modified. Notice that using == to compare person1 and person2 returns false, this is value based and not reference based comparison.

PersonRecord person1 = new PersonRecord("Alice", "Smith", new DateTime(1985, 5, 10));
Console.WriteLine(person1);

// Creating a new record with a modified property using the 'with' expression
PersonRecord person2 = person1 with { LastName = "Jones" };
Console.WriteLine(person2);

Console.WriteLine(person1 == person2); // Output: False

Real-Life Use Case

Records are excellent for representing data transfer objects (DTOs), representing results from database queries, or any scenario where you want a simple, immutable data structure with built-in value-based equality.

Best Practices

  • Use records when you need a simple, immutable data structure with value-based equality.
  • Use the `with` expression for creating new instances with modifications.
  • Be aware of the potential performance implications of creating new instances frequently.

Interview Tip

Be able to explain the advantages of using records over traditional classes for creating immutable data structures. Understand the features that records provide automatically (equality, `ToString()`, `with` expression).

When to use them

Records excel when representing immutable data. Examples include configuration settings, events, and data transfer objects.

Memory Footprint

Records generally have a similar memory footprint to classes with the same fields. As with immutable classes, 'modifying' a record requires creating a new instance, potentially increasing memory allocation compared to mutable alternatives.

Alternatives

  • Classes: Traditional classes can be made immutable, though with more boilerplate code.
  • Structs: Value types that can be immutable, but are best suited for small data structures due to their copy-by-value semantics.

Pros

  • Concise Syntax: Reduces the amount of code required for immutable data structures.
  • Value-Based Equality: Built-in equality comparison based on property values.
  • 'with' Expression: Simplifies creating new instances with modifications.

Cons

  • Limited Flexibility: Less flexible than classes for complex scenarios requiring custom behavior.
  • Newer Feature: Requires C# 9 or later.

FAQ

  • Can I add methods to a record?

    Yes, you can add methods to a record, just like you can with a class.
  • Are records reference types or value types?

    Records are reference types (classes) by default. You can define a `record struct` which is a value type.