What is the difference between value types and reference types in C#, and how does this affect variable assignment?
Short answer
Value types (primitives like int/bool, plus struct and enum) store their actual data directly wherever the variable lives, so assigning one variable to another copies the value -- modifying the copy never affects the original.
Advertisement
AModel answer
Value types (primitives like int/bool, plus struct and enum) store their actual data directly wherever the variable lives, so assigning one variable to another copies the value -- modifying the copy never affects the original. Reference types (class, array, delegate, interface) store a reference (memory address) to data on the heap, so assigning one variable to another copies just the reference, meaning both variables end up pointing at the same underlying object and a change through either one is visible through both.
// Value type: assignment copies the data
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a); // 10 -- unaffected
// Reference type: assignment copies the reference
class Person { public string Name; }
var p1 = new Person { Name = "Alice" };
var p2 = p1;
p2.Name = "Bob";
Console.WriteLine(p1.Name); // "Bob" -- p1 and p2 point to the same objectReal-world example
A bug where updating one object in a list appears to unexpectedly change a completely separate variable is traced to both variables referencing the identical heap object (a reference type), resolved once the developer explicitly clones the object rather than assuming assignment created an independent copy.
Likely follow-ups
- Why does passing a struct to a method not let that method modify the caller's original value, unless 'ref' is used?
- How does boxing turn a value type into something that behaves like a reference type?
Related topics