What are the differences between value types and reference types?
Short answer
Value types store their actual data directly within their own memory allocation, typically on the stack, and copying a value type variable creates a completely independent copy of the data, so changing one copy does not affect the other.
Advertisement
AModel answer
Value types store their actual data directly within their own memory allocation, typically on the stack, and copying a value type variable creates a completely independent copy of the data, so changing one copy does not affect the other. Reference types store a reference to data located on the heap, so copying a reference type variable only copies the reference itself, meaning both variables end up pointing to and sharing the exact same underlying object, and changing the data through one variable is visible through the other as well.
int a = 5;
int b = a;
b = 10; // a is still 5
Customer c1 = new Customer { Name = "Ali" };
Customer c2 = c1;
c2.Name = "Sara"; // c1.Name is now also "Sara"Real-world example
A developer fixing a bug discovers that modifying one Customer object unexpectedly changed a second variable's data as well, and realizes both variables were simply referencing the exact same object in memory since Customer is a reference type.
Likely follow-ups
- What are structs and why are they considered value types even though they can contain multiple fields?
- How does passing value types versus reference types into a method differ?
Related topics