C#

Value vs Reference Types

6 question(s)

What is the difference between a value type and a reference type?

Beginner
Value types (struct, enum, primitives) hold their data directly and are copied on assignment; reference types (class, array, string, delegate) hold a reference to data on the heap, so assignment copies the reference.
int a = 1; int b = a; b++;       // a stays 1
var l1 = new List<int>(); var l2 = l1; l2.Add(9); // l1 also has 9
Real-world example Passing a struct point copies it; passing a class order shares the same instance.

Where are value types and reference types stored?

Beginner
Local value types typically live on the stack; reference-type objects live on the managed heap with the reference on the stack. Value-type fields inside a class live on the heap with the object.
class Box { public int N; }   // N lives on the heap inside Box
int local = 5;                // stack
Real-world example Understanding this explains why large structs are costly to copy.

What is boxing and unboxing, and why does it matter?

Intermediate
Boxing wraps a value type in a heap object (implicit); unboxing extracts it (explicit cast). Both allocate/copy and hurt performance in loops.
int n = 42;
object boxed = n;      // boxing
int back = (int)boxed; // unboxing
Real-world example Non-generic ArrayList boxes every int; List<int> avoids it entirely.

When should you define a struct instead of a class?

Intermediate
Use a struct for small, immutable, value-like data (under ~16 bytes) that is copied cheaply and has value semantics; otherwise use a class. Mutable structs are error-prone.
public readonly struct Money(decimal Amount, string Currency);
Real-world example Coordinates, money, or a date range are natural structs; an entity with identity is a class.

How do nullable value types (int?) work under the hood?

Advanced
int? is Nullable<int>, a struct with HasValue and Value. The compiler lifts operators so null propagates; boxing a null Nullable<T> boxes to a real null reference.
int? x = null;
object o = x;              // o is null
int safe = x.GetValueOrDefault();
Real-world example Mapping a nullable database column to int? preserves 'no value' distinctly from 0.

Why can mutable structs cause subtle bugs?

Advanced
Because structs copy on assignment and when stored in some collections/properties, mutating a copy does not change the original — leading to lost updates. Prefer readonly structs.
struct P { public int X; }
var list = new List<P>{ new P() };
list[0].X = 5; // compile error / would mutate a copy
Real-world example A mutable struct field on a class property silently discards writes.