C# Records vs Classes: What's the Difference?
C# records and classes can both represent objects, but they are designed with different goals. Classes are the traditional choice for objects with identity and mutable state, while records are especially useful for data-centric models where value-based equality is important.
đˇī¸ A Simple Class
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
Two class instances are normally compared by reference unless equality is explicitly implemented.
đĻ A Simple Record
public record Customer(string Name, int Age);
Records provide compiler-generated value-oriented equality based on their data.
var a = new Customer("Dhilip", 31);
var b = new Customer("Dhilip", 31);
Console.WriteLine(a == b); // True
âī¸ Equality Is the Big Difference
For many record scenarios, two objects containing the same values are considered equal. A normal class does not behave that way by default.
public class Product
{
public int Id { get; set; }
}
var p1 = new Product { Id = 10 };
var p2 = new Product { Id = 10 };
Console.WriteLine(p1 == p2); // False
đ Non-Destructive Updates with with
Records work particularly well with the with expression:
var original = new Customer("Dhilip", 31);
var updated = original with { Age = 32 };
The original record remains unchanged while a new value is produced.
đ§ Records and Immutability
Records are not automatically immutable in every possible form, but positional records naturally encourage immutable-style models.
public record Customer(string Name, int Age);
This is particularly convenient for DTOs, messages, configuration snapshots, and other data-transfer scenarios.
đ§Š When Should You Use a Class?
- The object has a strong identity.
- The object changes state frequently.
- You need inheritance or object-oriented behavior.
- Reference identity is meaningful.
- The object represents an entity managed by a lifecycle.
đ¯ When Should You Use a Record?
- The object mainly represents data.
- Value-based equality is useful.
- You prefer immutable-style models.
- You are representing commands, events, or DTOs.
- You want convenient non-destructive updates.
đ§ Quick Rule
If identity matters, start by considering a class. If the values are the important part, consider a record.
For more C# fundamentals, visit đģ C# Tutorials.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.