C# Performance & Design: When to Use record vs class
In modern C# development (C# 9 through C# 13), choosing
between a class and a record (or record struct) is a fundamental architectural
decision. While both represent data structures, they serve entirely different
paradigms in software design: Object-Oriented Mutability versus Data-Centric
Immutability.
1. Fundamental Differences
- Value
Equality vs Reference Equality: Classes compare references by default
(two separate objects with identical property values are NOT equal).
Records automatically implement value-based equality.
- Immutability
by Default: Record positional syntax automatically generates init-only
properties, preventing accidental side effects in multi-threaded
environments.
- Built-in
Formatting: Records automatically override .ToString() to display
formatted property names and values, whereas classes display the type's
namespace string by default.
- Nondestructive
Mutation: Records support the with expression, allowing you to create
shallow copies with modified properties effortlessly.
2. Comparison Matrix
|
Feature |
class |
record (Reference Type) |
|
Primary Use Case |
Domain Entities, Business Logic, Services |
DTOs, API Requests/Responses, Value Objects |
|
Default Equality |
Reference Equality |
Value-Based Equality |
|
Immutability |
Mutable by default (get; set;) |
Immutable by default (init) |
|
Mutation Syntax |
Direct assignment (obj.Prop = x) |
with expressions (obj with { Prop = x }) |
|
ToString() Output |
Namespace.ClassName |
RecordName { Prop = Val } |
3. Principal Engineer Rules of Thumb
- Use
Records for Data Containers: Data Transfer Objects (DTOs), API
Contracts, Event Bus Messages, and Value Objects should be record types.
- Use
Classes for Stateful Entities & Services: Database models with
lifecycle states (EF Core Entities), Dependency Injection services
(Services, Repositories), and stateful domain objects belong in class
structures.
- Threading
Safety: Favor record for concurrent systems—immutable data eliminates
race conditions by default.
0 Comments
If you have any queries, please let me know. Thanks.