Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 182 ยท Variables and Types

Value Types and Reference Types

Understand C# value types and reference types - copy semantics, null, the stack and heap, boxing, struct vs class, the type hierarchy and ReferenceEquals.

Every type in C# belongs to one of two families, and the family decides what happens when you write b = a. For a value type, b receives its own copy of the data. For a reference type, b receives a copy of a reference, so both names point to the same object. Many beginner bugs ("I changed one thing and another changed too", "my method didn't change my number") come from not knowing which family a type is in.

This lesson builds the mental model: what each family stores, how assignment and method calls behave, what null means, how the stack and heap fit in (and where that picture is only a simplification), what boxing is, and how to compare values and references.

Two families

Value types Reference types
Declared with struct, enum, record struct class, record, interface, delegate, arrays
Examples int, double, bool, char, decimal, DateTime, tuples string, object, List<T>, arrays, your classes
A variable holds The data itself A reference (address) to an object
Assignment Copies the data Copies the reference
Can be null? No (unless int? and similar) Yes (string? makes it explicit)
Default value All zero bits null

Every value type derives from System.ValueType, which derives from System.Object. Every reference type derives from System.Object directly or through other classes. So everything is an object in the end, which is why a List<object> can hold numbers, text and your own classes alike.

Copy semantics of value types

Imagine a variable as a box. For a value type, the box contains the value. Assigning one variable to another makes a second box with a copy.

C# Value types are copied

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Changing b did not touch a, and changing p2.X did not touch p1. User-defined struct types behave exactly like int here. The same is true when you pass a value to a method: the method receives a copy, so changing the parameter inside does not change the caller's variable (unless you use ref; see Parameters).

Reference semantics of reference types

For a reference type, the variable's box holds an arrow to an object living elsewhere. Assigning copies the arrow, not the object.

C# Reference types share one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

After second.Value = 50, first.Value is also 50, because there is only one Counter. When we make second point to a new object, first is unaffected. That last point matters: assigning to a variable never changes the object it used to point at, it only changes where the variable points. The array example shows the same behavior for built-in reference types.

Passing references to methods

A reference is passed by value like everything else. The method receives a copy of the arrow. It can follow that arrow and modify the object, but reassigning its own parameter does not affect the caller.

C# Changing the object versus reassigning the parameter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The stack, the heap and the truth

A common explanation says "value types live on the stack, reference types on the heap". It is a useful first picture, with caveats.

  • The stack is a fast region organized per method call. Local variables and parameters of a running method live there, and they vanish when the method returns.
  • The heap is a larger region where objects live until the garbage collector finds that nothing refers to them any more (see Garbage Collection).
  • A reference-type variable holds a reference (typically in a local, so on the stack), and the object it points to is on the heap.

The caveats: a value type is stored inside whatever contains it. A Point field of a class lives on the heap as part of that class object. An int inside a List<int> lives inside the list's heap array. The JIT may also keep locals in CPU registers or, for short-lived objects, apply optimizations that avoid heap allocation. So the precise rule is: value-type data lives where its variable lives; reference-type objects are allocated on the heap (in nearly all cases).

The practical consequences matter more than the diagram: copying a big struct costs time because every field is copied, while creating a lot of small objects costs the garbage collector work. We come back to both in Structs and Boxing, Unboxing and Value Semantics.

null: a reference to nothing

A reference variable can hold the special value null, meaning "no object". Using a member through a null reference throws NullReferenceException, the most common runtime error in C#.

C# NullReferenceException (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The program prints Before and then stops with Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. and a stack trace that names main.cs. (The compiler also warns CS8602: Dereference of a possibly null reference, because text is declared as nullable; see Nullable Reference Types.)

Value types cannot be null, because their box holds data, not an arrow. When you need "no value" for a number, use a nullable value type, int?, which is a struct that pairs the value with a HasValue flag (Nullable Value Types).

Strings: a reference type that acts like a value

string is a reference type, but it is immutable: no method changes an existing string; they return a new one. Together with the fact that == on strings compares the text, strings feel like value types.

C# Strings are immutable references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because a was never modified, b = b.ToUpper() could not affect it. ReferenceEquals(a, c) is True since the compiler joins "hel" + "lo" into the literal "hello" and string literals are stored once (interned). The string d, built at run time, is a separate object with the same text. More on this in Strings.

Equality: ReferenceEquals, Equals and ==

There are three questions you can ask about two variables:

  1. Are they the same object? object.ReferenceEquals(x, y) answers it. For value types it is always false after boxing, because each boxed copy is a new object.
  2. Do they hold equal data? x.Equals(y). Value types compare their fields; for classes the default is the same as ReferenceEquals until the class overrides Equals.
  3. What does == do? It depends on the type. Primitives compare values; string and records are overloaded to compare content; a plain class uses reference comparison.
C# Same object or equal data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Plain classes use reference equality by default, so two boxes with the same size are not equal. A record generates value-based equality (see Records); overriding Equals yourself is the topic of The object Class.

Boxing: a value type becomes an object

Because every type derives from object, you can assign a value type to an object variable. The runtime then boxes it: it allocates an object on the heap and copies the value into it. Taking it back out with a cast is unboxing.

C# Boxing makes a copy on the heap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Boxing costs an allocation and a copy, so avoid it in hot code. It happens silently when you add value types to a non-generic collection, pass them to a parameter of type object or use them as an interface. Generic collections such as List<int> avoid it; that is a big reason generics exist (Generics).

Choosing struct or class

A first rule of thumb for your own types: use a class by default. Consider a struct only for small, short-lived, immutable data that represents a single value, like a point, a color or a money amount, ideally 16 bytes or less. Large or frequently changed data in a struct is copied again and again; a struct that is boxed or stored in collections loses its advantage. The decision gets a complete treatment in Structs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After int a = 5; int b = a; b = 8; what is a?

    int is a value type, so b received a copy. Changing b leaves a untouched.
  2. 2. Two variables hold the same instance of a class. You change a field through the first variable. What does the second variable see?

    Assignment of a reference type copies the reference, not the object, so both variables see the same object and its changes.
  3. 3. A method receives a List<int> parameter and runs items = new List<int>();. What happens to the caller's list?

    References are passed by value. Reassigning the parameter changes only the local copy; modifying the object (items.Add) would be visible to the caller.
  4. 4. What does object o = 7; do?

    Assigning a value type to object boxes it, which allocates and copies. Unboxing needs a cast to the exact original type.
  5. 5. Which type is NOT a value type?

    string is a (immutable) reference type. DateTime, bool and decimal are structs.

Summary

  • Value types (struct, enum, numbers, bool, char) hold their data directly and are copied on assignment; reference types (class, record, string, arrays, delegates) hold a reference and share one object.
  • Methods receive a copy of the variable: for a reference that means they can modify the shared object but cannot repoint the caller's variable.
  • null means "no object" and exists only for reference types and Nullable<T>; dereferencing it throws NullReferenceException.
  • Value data lives wherever its variable lives (stack, inside an object, inside an array); reference-type objects live on the heap and are freed by the garbage collector.
  • string is an immutable reference type whose == compares content; ReferenceEquals asks whether two references point to the same object.
  • Boxing copies a value type into a new heap object; unboxing needs the exact type and both have a cost.
  • Default to a class; use a struct only for small, immutable, value-like data.

Next: Integer Types