Struct Vs Class When To Use Which ยท TL;DR
1 min readRapid overview
TL;DR
| Feature | struct | class |
|---|---|---|
| Type category | Value type | Reference type |
| Memory allocation | Stored inline wherever its container lives โ a local's stack slot (or a register), a field inside a heap object, an array element. Boxed copies go to the heap | Instance on the heap; the variable holds a reference |
| Default behavior | Copied by value (creates a full copy) | Copied by reference (points to same object) |
| Nullability | Cannot be null (unless Nullable<T>) | Can be null |
| Inheritance | Cannot inherit from another struct or class; only from ValueType | Supports inheritance and polymorphism |
| Interfaces | Can implement interfaces | Can implement interfaces and base classes |
| Default constructor | Always has an implicit public parameterless ctor that zeroes every field. C# 10+ lets you declare one, but it must be public, and default(T) / new T[n] skip it | Can freely define constructors |
| Equality | ValueType.Equals compares fields (may use reflection โ slow); no == unless you define it (record struct generates both) | Reference equality unless overridden (record generates value equality) |
| Records | record struct / readonly record struct (C# 10) | record / record class (C# 9) |
| Finalizer / Destructor | Not supported | Supported |
| GC behavior | Not a separate GC object: reclaimed with its container (stack frame pops, or the owning heap object is collected) | Each instance tracked by the Garbage Collector |
| Boxing / Unboxing | Converting to/from object/interface causes allocation | No boxing/unboxing issues |
| Thread safety | Safer for small immutable data | Reference types require synchronization if shared |