Advanced C# Features: Records
Quick Answer
C# Records are a reference type introduced in C# 9.0 designed for immutable data models. They provide built-in value-based equality, concise syntax, and support for non-destructive mutation, making them ideal for scenarios where data immutability and simplicity are important.
Learning Objectives
- Explain the purpose of Records in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Records.
- Apply Records in a simple real-world scenario or practice task.
Introduction to C# Records
Records are a powerful feature introduced in C# 9.0 that simplify working with immutable data.
They provide a concise syntax for defining data-centric types with built-in value equality and immutability support.
Immutability is a key principle for safer and more predictable code.
What Are Records in C#?
Records are reference types that provide value-based equality semantics by default.
Unlike classes, records are designed to represent immutable data with less boilerplate code.
- Declared using the 'record' keyword.
- Automatically generate equality members (Equals, GetHashCode).
- Support positional syntax for concise property declarations.
- Enable non-destructive mutation with the 'with' expression.
Defining Records
You can define a record using positional syntax or with explicit property declarations.
Positional records declare properties directly in the record header.
Positional Record Example
This example defines a record with two properties using positional syntax.
Record with Properties Example
You can also define a record with explicit properties and custom logic.
Value Equality in Records
Records override Equals and GetHashCode to compare values of properties instead of references.
This makes comparing two record instances with the same data return true.
- Equality is based on all positional parameters or properties.
- Simplifies comparing data objects without writing custom equality code.
Immutability and Non-Destructive Mutation
Records encourage immutability by default, with init-only properties.
The 'with' expression allows creating a new record instance by copying an existing one with some properties changed.
- Init-only setters prevent modification after object creation.
- The 'with' expression supports safe, non-destructive updates.
When to Use Records
Records are ideal for data models where immutability and value equality are important.
Common use cases include DTOs, configuration objects, and data transfer between layers.
- Use records for immutable data structures.
- Avoid records if mutable state or complex behavior is required.
Practical Example
Defines a record 'Person' with two immutable properties using concise positional syntax.
Creates a new 'Person' instance by copying 'person1' and changing the 'LastName' property.
Two record instances with the same data are considered equal due to value-based equality.
Examples
public record Person(string FirstName, string LastName);Defines a record 'Person' with two immutable properties using concise positional syntax.
var person1 = new Person("Alice", "Smith");
var person2 = person1 with { LastName = "Johnson" };Creates a new 'Person' instance by copying 'person1' and changing the 'LastName' property.
var p1 = new Person("John", "Doe");
var p2 = new Person("John", "Doe");
bool areEqual = p1 == p2; // trueTwo record instances with the same data are considered equal due to value-based equality.
Best Practices
- Use records for immutable data models to reduce boilerplate code.
- Prefer positional syntax for simple records with few properties.
- Use 'with' expressions to create modified copies instead of mutating existing instances.
- Avoid adding mutable fields to records to maintain immutability benefits.
- Leverage value equality for comparing data objects instead of reference equality.
Common Mistakes
- Treating records like mutable classes and modifying properties after creation.
- Using records for types that require complex behavior or mutable state.
- Ignoring the difference between reference equality and value equality.
- Overusing records when simple classes would be more appropriate.
Hands-on Exercise
Create a Record for a Book
Define a record named 'Book' with properties for Title, Author, and ISBN using positional syntax.
Expected output: A record 'Book' with three immutable properties.
Hint: Use the 'record' keyword and define properties inside parentheses.
Use 'with' to Modify a Record
Create an instance of the 'Book' record and then create a new instance with a different ISBN using the 'with' expression.
Expected output: A new 'Book' instance with the updated ISBN.
Hint: Use the 'with' keyword to copy and modify properties.
Compare Two Records
Create two 'Book' record instances with the same data and check if they are equal.
Expected output: The comparison should return true.
Hint: Use the equality operator '==' to compare records.
Interview Questions
What is the main difference between a class and a record in C#?
InterviewRecords provide built-in value-based equality and are designed for immutable data, while classes use reference equality and are typically mutable.
How does the 'with' expression work with records?
InterviewThe 'with' expression creates a new record instance by copying an existing one and allowing selective property modifications without changing the original.
Can records have mutable properties?
InterviewWhile possible, it is discouraged because records are intended to be immutable to leverage value equality and thread safety.
MCQ Quiz
1. What is the best first step when learning Records?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Records?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. C# Records are a reference type introduced in C# 9.0 designed for immutable data models.
B. Records never needs examples
C. Records is unrelated to practical work
D. Records should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- C# Records are a reference type introduced in C# 9.0 designed for immutable data models.
- They provide built-in value-based equality, concise syntax, and support for non-destructive mutation, making them ideal for scenarios where data immutability and simplicity are important.
- Records are a powerful feature introduced in C# 9.0 that simplify working with immutable data.
- They provide a concise syntax for defining data-centric types with built-in value equality and immutability support.
- Records are reference types that provide value-based equality semantics by default.
Summary
C# Records are a modern feature that simplify creating immutable data types with value-based equality.
They reduce boilerplate code and improve code clarity for data-centric applications.
Understanding records and their features like the 'with' expression is essential for writing clean, maintainable C# code.
Frequently Asked Questions
When were records introduced in C#?
Records were introduced in C# 9.0, released with .NET 5 in 2020.
Can records inherit from classes?
Records can inherit from other records but cannot inherit from classes.
Are records mutable by default?
No, records use init-only properties by default, making them immutable after initialization.
Do records support inheritance?
Yes, records support inheritance but only from other records, enabling polymorphic data models.
What is Records?
C# Records are a reference type introduced in C# 9.0 designed for immutable data models.
Why is Records important?
They provide built-in value-based equality, concise syntax, and support for non-destructive mutation, making them ideal for scenarios where data immutability and simplicity are important.

