Value types and reference types

Assigning a struct copies the data. Assigning a class instance copies only the reference to it.

Time copy: O(size)Space stack / heapCode C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A value-type variable holds the data itself. A reference-type variable holds an address of an object on the heap. So "copy" means two different things depending on the type.

Code

struct Point { public int X; }      // value type
class Box { public int X; }         // reference type

Point p1 = new Point { X = 1 };
Point p2 = p1;                      // copies the value
p2.X = 9;

Box b1 = new Box { X = 1 };
Box b2 = b1;                        // copies the reference
b2.X = 9;
Console.WriteLine(p1.X + " " + b1.X);   // 1 9

Tips

In the .NET library

A record class is still a reference type, but it compares by value. A record struct is a value type. Choose struct only for small, immutable data.