C# Class vs Record: Understanding the Differences

With the release of C# 9.0, a new reference type called record was introduced, offering a more concise way to define immutable data structures. While traditional classes remain a core part of the language, it's important to understand how records differ and when to use one over the other. In this post, we’ll explore the differences between classes and records in C#, and provide guidance on choosing the right one for your scenario.
1. What is a Class in C#?
A class in C# is a reference type used to define objects with properties, methods, and behaviors. Classes are mutable by default, meaning their internal state can be changed after instantiation.
2. What is a Record?
A record is a special kind of reference type introduced in C# 9.0. It is intended for immutable data models and supports built-in value-based equality comparison. Records are ideal for scenarios where the main purpose is to hold data, such as DTOs or event payloads.
3. Key Differences Between Class and Record
- Mutability: Classes are mutable by default; records are immutable unless explicitly defined as mutable.
- Equality: Classes use reference equality by default, while records use value-based equality.
- Conciseness: Records offer a concise syntax for data models with `init` properties and built-in `ToString()`, `Equals()`, and `GetHashCode()` implementations.
- Inheritance: Both support inheritance, but records introduce `with` expressions and support for value-like cloning.
4. Example: Class vs Record
Here’s a simple comparison to show how a class and a record behave differently:
// Class example
public class PersonClass
{
public string Name { get; set; }
public int Age { get; set; }
}
// Record example
public record PersonRecord(string Name, int Age);
When you compare two objects of each type:
var p1 = new PersonClass { Name = "John", Age = 30 };
var p2 = new PersonClass { Name = "John", Age = 30 };
Console.WriteLine(p1 == p2); // False (reference equality)
var r1 = new PersonRecord("John", 30);
var r2 = new PersonRecord("John", 30);
Console.WriteLine(r1 == r2); // True (value equality)
5. When to Use Class vs Record?
- Use class when you need a rich object with behaviors, mutability, or identity-based equality.
- Use record when you need simple, immutable data containers and prefer value-based equality.
6. Final Thoughts
Both classes and records have their place in C#. Understanding their differences helps you write clearer and more maintainable code. Records shine when working with data models, while classes offer flexibility for complex logic and behavior. Choose the right tool based on the problem you're solving.