Class vs Struct in C#: Key Differences and When to Use Each
class is a reference type stored on the heap and supports inheritance, while a struct is a value type stored on the stack and does not support inheritance. Use class for complex objects requiring reference semantics and struct for small, simple data containers.Quick Comparison
Here is a quick side-by-side comparison of class and struct in C# highlighting their main differences.
| Aspect | Class | Struct |
|---|---|---|
| Type | Reference type | Value type |
| Memory allocation | Heap | Stack (usually) |
| Inheritance | Supports inheritance | No inheritance (except interfaces) |
| Default constructor | Can define custom | Cannot define custom parameterless |
| Nullability | Can be null | Cannot be null (unless nullable struct) |
| Typical use | Complex objects | Small data containers |
Key Differences
Class is a reference type, meaning when you assign or pass it, you copy the reference (address), not the actual data. This allows multiple variables to refer to the same object in memory. Struct, on the other hand, is a value type, so assigning or passing it copies the entire data, creating independent copies.
Because class instances live on the heap, they support inheritance and polymorphism, allowing you to create complex object hierarchies. Struct types do not support inheritance except for implementing interfaces, making them simpler and more lightweight.
Another difference is that struct cannot have a custom parameterless constructor and always has an implicit default constructor that initializes all fields to default values. Class can have custom constructors and can be null, while struct cannot be null unless wrapped in Nullable<T>.
Code Comparison
Here is an example showing a class representing a point with X and Y coordinates.
public class PointClass { public int X { get; set; } public int Y { get; set; } public PointClass(int x, int y) { X = x; Y = y; } } // Usage var p1 = new PointClass(1, 2); var p2 = p1; // p2 references the same object p2.X = 5; System.Console.WriteLine(p1.X); // Output: 5
Struct Equivalent
Here is the same example using a struct instead of a class.
public struct PointStruct { public int X { get; set; } public int Y { get; set; } public PointStruct(int x, int y) { X = x; Y = y; } } // Usage var p1 = new PointStruct(1, 2); var p2 = p1; // p2 is a copy p2.X = 5; System.Console.WriteLine(p1.X); // Output: 1
When to Use Which
Choose class when you need reference semantics, inheritance, or your object is large and complex. This is common for entities, services, or objects that share state.
Choose struct when you want a lightweight, immutable data container with value semantics, such as points, colors, or small data records. Structs reduce heap allocations and improve performance in these cases.
Remember that structs should be small and simple to avoid performance costs from copying large value types.