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
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
Pros
Cons
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.