A C# variable either holds its data directly or holds a pointer to data somewhere else. That single distinction decides how assignment, method calls, equality, and garbage collection behave. This guide uses memory diagrams and short, isolated code samples to show exactly what happens in each case.
Quick Takeaways
- Value types (
int,bool,struct,enum) store their data inside the variable. Assignment copies the data. - Reference types (
class,interface,delegate,string, arrays) store a pointer to an object on the managed heap. Assignment copies the pointer, not the object. - A struct is not always on the stack. A struct field inside a class lives on the heap, and a boxed struct is a heap object.
- Use a struct for small, immutable, short-lived data (about 16 bytes or less). Use a class for everything else.
What Separates Value Types from Reference Types?
Every C# type derives from System.Object. Types that derive from System.ValueType are value types. All others are reference types.
Value Types
| Category | Examples |
|---|---|
| Numeric primitives | int, long, double, decimal, byte |
| Other primitives | bool, char |
| User-defined | struct, record struct, enum |
| Wrappers | Nullable<T> (int?), DateTime, Guid, ValueTuple |
Reference Types
| Category | Examples |
|---|---|
| User-defined | class, record (class), interface, delegate |
| Built-in | string, object, dynamic |
| Collections | arrays (even int[]), List<T>, Dictionary<TKey,TValue> |
An int[] is a reference type even though its elements are value types. The array object lives on the heap, and the variable holds a pointer to it.
Memory Layout: A Visual Model
Picture two regions. The stack holds local variables and frames. The managed heap holds objects and is cleaned up by the garbage collector.
STACK (locals) HEAP (objects)
┌──────────────────┐
│ int a = 10 │ (nothing on the heap)
├──────────────────┤
│ int b = 20 │
├──────────────────┤ ┌────────────────────┐
│ Person p ───────────────────────►│ Person object │
│ (8-byte pointer) │ │ Name = "Ada" │
└──────────────────┘ │ Age = 36 │
└────────────────────┘
The variable a is the number 10. The variable p is an address that leads to the object. This explains almost every behavioral difference below.
Edge case: location depends on where the variable lives, not on the type alone. A struct declared as a local usually sits on the stack (or in a register). The same struct as a field of a class sits inside that class’s heap object.
class Order { Point Location; } // Point is a struct
HEAP
┌─────────────────────────┐
│ Order object │
│ ┌───────────────────┐ │
│ │ Location (struct) │ │ ← struct data stored inline, on the heap
│ │ X = 3, Y = 7 │ │
│ └───────────────────┘ │
└─────────────────────────┘
Assignment Semantics: Copy vs Share
Value type assignment
int a = 10;
int b = a; // copies the value 10 into b
b = 20;
Console.WriteLine(a); // 10
Console.WriteLine(b); // 20
Each variable owns its data. Changing b never touches a.
Reference type assignment
public class Person
{
public string Name { get; set; } = "";
}
var p1 = new Person { Name = "Ada" };
var p2 = p1; // copies the pointer, not the object
p2.Name = "Grace";
Console.WriteLine(p1.Name); // Grace
Console.WriteLine(p2.Name); // Grace
Both variables point to one object. A change through p2 is visible through p1.
Struct assignment
public struct Point
{
public int X;
public int Y;
}
var s1 = new Point { X = 1, Y = 2 };
var s2 = s1; // full copy of both fields
s2.X = 99;
Console.WriteLine(s1.X); // 1
Console.WriteLine(s2.X); // 99
A struct copies its data field by field. This is why Point behaves like int and not like Person.
After: var s2 = s1; After: var p2 = p1;
s1 [X=1 ][Y=2] p1 ──┐
s2 [X=1 ][Y=2] (copy) p2 ──┴──► [ Person object ] (shared)
Passing Arguments to Methods
By default, C# passes everything by value. For reference types, the value being copied is the pointer.
static void Increment(int n) => n++; // modifies a local copy
static void IncrementRef(ref int n) => n++; // modifies the caller's variable
int count = 5;
Increment(count);
Console.WriteLine(count); // 5
IncrementRef(ref count);
Console.WriteLine(count); // 6
The first call changes a copy. The second call passes the variable’s address, so the change persists.
Now the reference-type case, which trips up many developers:
static void Rename(Person p) => p.Name = "Changed"; // follows the pointer
static void Replace(Person p) => p = new Person { Name = "New" }; // rebinds local pointer only
var person = new Person { Name = "Original" };
Replace(person);
Console.WriteLine(person.Name); // Original
Rename(person);
Console.WriteLine(person.Name); // Changed
Rename mutates the shared object, so the caller sees it. Replace only repoints its own copy of the pointer. Add the ref keyword to Replace and the caller’s variable would be repointed too.
Parameter modifiers at a glance
| Modifier | Meaning | Typical use |
|---|---|---|
| (none) | Copy of value or pointer | Default for small data |
| ref | Alias to caller’s variable, read/write | Swap, in-place update |
| out | Callee must assign before returning | TryParse patterns |
| in | Read-only alias, avoids copying | Large readonly struct inputs |
Boxing and Unboxing
Boxing wraps a value type in a heap object when it is converted to object or an interface. Unboxing extracts it again.
int x = 42;
object boxed = x; // allocates a heap object holding a copy of 42
x = 99; // does not affect the box
int y = (int)boxed; // unboxing: type check, then copy out
Console.WriteLine(y); // 42
The box holds an independent copy. Every boxing operation allocates, which adds GC pressure in hot loops.
// Boxes every element: ArrayList stores object
var legacy = new System.Collections.ArrayList();
legacy.Add(1);
// No boxing: List<int> stores ints inline in its backing array
var modern = new List<int> { 1 };
Generic collections avoid boxing entirely. Prefer them in all new code.
Equality: Value vs Reference
Reference types compare identity by default. Value types compare contents, though a plain struct falls back to a slower general-purpose comparison unless you implement IEquatable<T>.
public sealed class Account { public int Id { get; init; } }
public readonly record struct Money(decimal Amount, string Currency);
var a1 = new Account { Id = 1 };
var a2 = new Account { Id = 1 };
Console.WriteLine(a1 == a2); // False: different objects
var m1 = new Money(10m, "USD");
var m2 = new Money(10m, "USD");
Console.WriteLine(m1 == m2); // True: same contents
A record struct generates value-based equality for you, including IEquatable<T>, ==, and GetHashCode(). A record class also compares by value, while still being a reference type.
The string Special Case
string is a reference type with value-like behavior. It is immutable, and it overloads == to compare characters.
string s1 = "hello";
string s2 = s1;
s2 += " world"; // creates a NEW string; s1 is untouched
Console.WriteLine(s1); // hello
Console.WriteLine(s2); // hello world
Immutability means shared pointers never cause surprise mutations. For heavy concatenation, use StringBuilder to avoid allocating a new string on each append.
Side-by-Side Comparison
| Aspect | Value Type | Reference Type |
|---|---|---|
| Holds | The data itself | A pointer to a heap object |
| Assignment | Copies data | Copies pointer |
| Default value | Zeroed (0, false) |
null |
Can be null |
Only via Nullable<T> | Yes |
| Equality default | Content-based | Identity-based |
| Inheritance | None (sealed; interfaces only) | Single class inheritance |
| GC cost | None if on stack; part of owner if inline | Allocation + collection |
| Boxing | Possible | Not applicable |
| Best for | Small immutable values | Entities, services, large data |
Choosing Between struct and class
Microsoft’s design guidance favors a struct only when all of these hold:
- It logically represents a single value, like
int. - Its instance size is small (roughly 16 bytes or less).
- It is immutable.
- It is not boxed frequently.
If any condition fails, use a class. Copying a 64-byte struct on every method call can cost more than one heap allocation.
Bad Code vs Good Code
Anti-pattern: large mutable struct, boxing, and list mutation
// BAD
public struct Order
{
public int Id;
public string Customer;
public decimal Total;
public DateTime Created;
public List<string> Items; // reference inside a "value": shallow-copy trap
}
var orders = new List<Order> { new Order { Id = 1 } };
// orders[0].Total = 50m; // compile error CS1612: returns a copy
var legacy = new System.Collections.ArrayList();
legacy.Add(5); // boxes the int
int n = (int)legacy[0]!; // unboxes
Problems: the struct exceeds the size guideline, it is mutable, and copying it duplicates the Items pointer without duplicating the list. The list indexer returns a copy, so modifying a field fails to compile. ArrayList boxes every int.
Refactored: right type for each job
// GOOD
public sealed class Order
{
public int Id { get; init; }
public string Customer { get; init; } = "";
public decimal Total { get; set; }
public DateTime Created { get; init; }
public List<string> Items { get; } = new();
}
public readonly record struct Money(decimal Amount, string Currency);
var orders = new List<Order> { new Order { Id = 1 } };
orders[0].Total = 50m; // works: modifies the shared object
var numbers = new List<int> { 5 };
int first = numbers[0]; // no boxing
Order is an entity with identity, so it becomes a class. Money is a small immutable value, so it stays a readonly record struct. The generic List<int> removes boxing.
Edge Cases Worth Knowing
Mutable structs cause silent bugs. Calling a mutating method on a readonly field operates on a defensive copy:
public struct Counter
{
public int Value;
public void Increment() => Value++;
}
class Holder { public readonly Counter C = new(); }
var h = new Holder();
h.C.Increment();
Console.WriteLine(h.C.Value); // 0, not 1: mutation hit a copy
Mark structs readonly to make the compiler reject this mistake.
Arrays of structs behave differently from lists. Array element access returns a reference to the slot, so points[0].X = 5 works. The List<T> indexer returns a copy, so the same line fails to compile.
Nullable value types are structs. int? is Nullable<int>, a struct with a HasValue flag and a Value field. It adds a byte (plus padding) and stays on the stack.
Performance Trade-offs
| Scenario | Faster choice | Reason |
|---|---|---|
| Millions of tiny objects in an array | struct | Contiguous memory, no per-object header, fewer GC objects |
| Passing a 100-byte object through many calls | class | Pointer copy is 8 bytes |
| Large struct as input | readonly struct + in |
Avoids the copy |
Frequent cast to object or interface |
class or generics | Avoids repeated boxing allocations |
Measure with BenchmarkDotNet before optimizing. Allocation counts and cache behavior often matter more than the type category.
FAQ
What is the main difference between value types and reference types in C#?
A value type variable stores its data directly, so assignment copies the data. A reference type variable stores a pointer to a heap object, so assignment copies the pointer and both variables share one object.
Are structs always stored on the stack?
No. A local struct often lives on the stack, but a struct field inside a class is stored inline in that object on the heap. A boxed struct is also a heap object. Storage depends on where the variable lives.
Is string a value type or a reference type in C#?
string is a reference type. It is immutable and overloads == to compare characters, so it behaves like a value type in everyday code.
When should I use a struct instead of a class?
Use a struct for small (about 16 bytes or less), immutable values that represent a single concept, such as coordinates, money, or identifiers. Use a class for larger data, mutable state, or objects that need identity or inheritance.




