Interview frequency: …
Short answer
Value Types inherit from System.ValueType and store their values directly (usually on the Stack or inside their containing object), while Reference Types inherit from System.Object and store references on the Stack that point to data in the Managed Heap.
Explanation
Value Types include structs, primitives, and enums, and are copied by value when passed. Reference Types include classes, interfaces, strings, and arrays; their references point to the same location on the Managed Heap, which the Garbage Collector reclaims.
Code example
// Value type
int a = 10;
int b = a; // Copy the value
b = 20; // a Remains 10
// Reference type
var user1 = new User { Name = "Ali" };
var user2 = user1; // Copy the reference
user2.Name = "Zaid"; // user1.Name Changes to ZaidCommon mistakes
- Believing that all Value Types are always stored only on the Stack; a value stored in a class field resides on the Heap as part of that object.
Follow-up questions
- What are Boxing and Unboxing in C#, and why should they be avoided in high-volume code paths?
- How do Nullable Reference Types work in C#, and what is the role of Static Flow Analysis?