Advertisement
Intermediate .NET, CLR & Runtime

How does the CLR's type system distinguish between value types and reference types, and where is each typically allocated?

Short answer

Value types (structs, primitives like int/bool/double) are typically allocated on the stack (or inline within a containing object/array) and copied by value when assigned or passed, offering fast allocation/deallocation with no garbage collection overhead.

Save .NET mock interview
Advertisement
AModel answer
Value types (structs, primitives like int/bool/double) are typically allocated on the stack (or inline within a containing object/array) and copied by value when assigned or passed, offering fast allocation/deallocation with no garbage collection overhead. Reference types (classes) are allocated on the managed heap, with variables holding a reference (pointer) to the heap location, requiring garbage collection to reclaim memory once no references remain.
struct Point { public int X, Y; }  // value type, typically stack-allocated
class Person { public string Name; }  // reference type, heap-allocated

Point p1 = new Point { X = 1, Y = 2 };
Point p2 = p1;  // COPY -- p2 is independent of p1

Person person1 = new Person { Name = "Alice" };
Person person2 = person1;  // REFERENCE -- both point to the same object
Real-world example
A performance-sensitive game engine uses structs extensively for small, frequently-created data like 2D/3D vectors specifically to avoid garbage collection pressure that would result from allocating millions of small reference-type objects per frame.
Likely follow-ups
  • When does a struct actually get boxed onto the heap despite being a value type?
  • What's the performance trade-off of large structs being copied by value?
Related topics