Value type vs reference type
Assigning a variable either copies the whole value (value types) or copies only a reference to a shared object (reference types). This one rule explains why changing a "copy" sometimes changes the original, and it is one of the most asked C# interview questions.
5.1 Problem: a copy or the same cart?
var cart = new Cart { Total = 500 }; var preview = cart;preview.Total -= 100; Console.WriteLine($"Preview {preview.Total}");Console.WriteLine($"Cart {cart.Total}"); class Cart{ public decimal Total { get; set; }}$ dotnet run CartBug.csPreview 400Cart 400- Step 1
1.new Cart creates one object; cart holds its reference (address)
- Step 2
2.preview = cart copies only the reference
- Step 3
3.Both variables point to the same Cart object
- Step 4
4.preview.Total -= 100 changes that one object
- Step 5
5.cart.Total also reads 400
Class = reference type: the address is copied, not the object
5.2 Struct: value type, full copy
- Change only one word: struct instead of class.
- A value type variable holds the whole value, so preview gets a complete, independent copy.
- int, double, decimal, bool are value types too: assigning one int to another gives an independent copy.
var cart = new Cart { Total = 500 }; var preview = cart;preview.Total -= 100; Console.WriteLine($"Preview {preview.Total}");Console.WriteLine($"Cart {cart.Total}"); struct Cart{ public decimal Total { get; set; }}$ dotnet run CartStruct.csPreview 400Cart 5005.3 Fix: a real copy of the class
- Do not turn everything into a struct: a cart that grows and changes should stay a class.
- For a real copy, create a new object and copy the values into it.
- cart == preview is False: for classes, == compares references by default, and these are two objects.
var cart = new Cart { Total = 500 }; var preview = new Cart { Total = cart.Total };preview.Total -= 100; Console.WriteLine($"Preview {preview.Total}");Console.WriteLine($"Cart {cart.Total}");Console.WriteLine(cart == preview); class Cart{ public decimal Total { get; set; }}$ dotnet run CartFix.csPreview 400Cart 500False5.4 Comparison: value type vs reference type
| Point | Value type | Reference type |
|---|---|---|
| Variable holds | The value itself | A reference to an object |
| Assignment / passing to a method | Full independent copy | Reference copied, object shared |
| Examples | int, double, decimal, bool, char, struct, enum | class, array, string, interface, delegate |
| Default == for the type | Compares values | Compares references (class) |
| Can be null? | Only as Nullable (int?) | Yes |
5.5 Stack and heap: mental model
- Step 1
1.A method runs: its locals live in a stack frame
- Step 2
2.new creates the object on the heap
- Step 3
3.The local variable holds a reference to the heap object
- Step 4
4.Method ends: its stack frame is removed
- Step 5
5.The garbage collector later cleans heap objects nobody references
A simplified model, not a rule
- Myth: "value types always live on the stack". Only half true.
- A struct field of a class lives on the heap with its object; int[] elements are on the heap.
- Locals captured by a lambda or used in an async method can move to the heap.
- The .NET 10 JIT can even put some small objects on the stack.
- The real difference is copy behavior, not location.
5.6 Boxing and unboxing
- Boxing: putting a value type into an object variable creates a box on the heap with a copy of the value.
- Changing stock afterwards does not change the box (box still 5).
- Unboxing: casting it back out, (int)box.
- Unboxing to the wrong type (long) throws InvalidCastException: the box holds an Int32.
int stock = 5;object box = stock; // boxingstock = 10; Console.WriteLine($"stock = {stock}");Console.WriteLine($"box = {box}"); int back = (int)box; // unboxingConsole.WriteLine($"back = {back}"); long wrong = (long)box;$ dotnet run Boxing.csstock = 10box = 5back = 5Unhandled exception. System.InvalidCastException:Unable to cast object of type 'System.Int32'to type 'System.Int64'.5.7 Checkpoint: arrays are reference types
int[] marks = [70, 80, 90];int[] copy = marks;copy[0] = 100; Console.WriteLine(marks[0]);$ dotnet run Checkpoint.cs100- The elements are ints, but the array itself is a reference type: marks and copy point to the same array.
5.8 Nullable value types: int?
- A normal int can never be null, but real data is often missing (an order with no discount).
- int? holds an int or null; HasValue tells whether there is a value.
- GetValueOrDefault() gives 0 for null.
- Reading .Value on null throws InvalidOperationException (the compiler warns with CS8629).
int? offer = null; Console.WriteLine(offer.HasValue);Console.WriteLine(offer.GetValueOrDefault()); offer = 15;Console.WriteLine(offer.HasValue);Console.WriteLine(offer.Value); int? coupon = null;Console.WriteLine(coupon.Value);$ dotnet run Nullable.cswarning CS8629: Nullable value type may be null.False0True15Unhandled exception.System.InvalidOperationException:Nullable object must have a value.5.9 Common mistakes
- Passing a struct to a method and expecting the caller to see changes: the method got a copy (prints 50).
- Fix: return the updated copy and store it back (score = AddBonus(score) prints 60).
- Thinking var preview = cart copies a class object.
- Boxing in loops: the old ArrayList boxes every int; List<int> does not.
var score = new Score { Points = 50 };score = AddBonus(score);Console.WriteLine(score.Points); // 60 static Score AddBonus(Score s){ s.Points += 10; return s;} struct Score{ public int Points { get; set; }}5.10 When to use which
- struct: small, simple data like a point or money; prefer it immutable.
- class: entities that grow and change (cart, order, customer).
- Need a real copy of a class: create a new object.
- Missing value for a value type: use T? and check HasValue before Value.
5.11 Interview tips
- Value type: the variable holds the value, so assigning or passing makes a full copy (int, decimal, struct).
- Reference type: the variable holds a reference, so after a copy both point to the same object (class, array, string).
- Stack vs heap is an implementation detail; the real difference is copy semantics.
- Boxing = putting a value type into object; it is an extra heap allocation.