Introduction
In modern C# development, choosing the right data type is very important for performance, readability, and maintainability. Developers often get confused between class, struct, and the newer record struct.
If you are working with .NET, APIs, or data models, understanding the difference between record struct and class can help you write cleaner and more efficient code.
In this article, we will explain everything in simple words with examples.
What is a Class in C#?
A class is a reference type in C#. This means when you create an object of a class, it is stored in the heap memory, and variables hold a reference (address) to that object.
Classes are widely used in object-oriented programming and support features like inheritance, polymorphism, and encapsulation.
Example:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Usage:
Person p1 = new Person { Name = "John", Age = 30 };
Person p2 = p1;
p2.Name = "Mike";
Console.WriteLine(p1.Name); // Output: Mike
Explanation:
Both p1 and p2 refer to the same object. So, changes in one affect the other.
What is a Record Struct in C#?
A record struct is a value type introduced in C# to combine the benefits of struct and record.
It is mainly used for immutable data and supports value-based equality.
Unlike class, record struct stores data directly (usually on the stack) and compares objects based on values, not references.
Example:
public readonly record struct Person(string Name, int Age);
Usage:
var p1 = new Person("John", 30);
var p2 = p1;
p2 = p2 with { Name = "Mike" };
Console.WriteLine(p1.Name); // Output: John
Explanation:
Here, p1 and p2 are separate copies. Changing p2 does not affect p1.
Key Differences Between Record Struct and Class
| Feature | Class | Record Struct |
|---|---|---|
| Type | Reference Type | Value Type |
| Memory Storage | Heap | Stack (mostly) |
| Equality | Reference-based | Value-based |
| Mutability | Mutable by default | Usually immutable |
| Performance | Slower (due to heap) | Faster (lightweight) |
| Use Case | Complex objects | Lightweight data models |
Join the conversation! Your thoughts help the community grow.