Introduction
In C# and .NET development, one of the most commonly asked and practically important questions is the difference between struct and class. While both are used to define custom data types, their behavior in memory, performance, and real-world usage is significantly different.
If misunderstood, choosing the wrong type can lead to performance issues, memory overhead, or unexpected bugs in large-scale applications.
In this article, we will deeply explore struct vs class in C#, including memory allocation, performance comparison, real-world scenarios, and when to use each.
What is a Class in C#?
A class in C# is a reference type. This means that when you create an object of a class, memory is allocated on the heap, and variables store references (addresses) to that memory.
Example
class Person
{
public string Name;
}
Person p1 = new Person();
p1.Name = "Rahul";
Person p2 = p1;
p2.Name = "Amit";
Output Behavior
Both p1 and p2 will have Name = "Amit" because they point to the same memory location.
Real-World Analogy
Think of a class as a Google Drive file link. Multiple people can access and modify the same file using the same reference.
What is a Struct in C#?
A struct in C# is a value type. It stores data directly, usually on the stack, and copies values when assigned.
Example
struct Person
{
public string Name;
}
Person p1 = new Person();
p1.Name = "Rahul";
Person p2 = p1;
p2.Name = "Amit";
Output Behavior
p1.Name remains "Rahul" because struct creates a copy of data.
Real-World Analogy
Think of struct like a printed document. If you copy it, each person gets their own separate version.
Memory Allocation: Stack vs Heap
Understanding memory behavior is key to performance optimization in .NET applications.
Class → Stored in Heap
Struct → Stored in Stack (in most cases)
Why This Matters
Heap allocation is slower and requires garbage collection
Stack allocation is faster and automatically managed
Join the conversation! Your thoughts help the community grow.