Skip to content
Codescope

struct vs class

One keyword decides whether assignment copies the data or just the handle.

intro8 min6 steps

Before you start

In C#, the single most important type-system decision is struct versus class. It looks like a cosmetic choice of keyword. It is not.

A struct is a **value type** — the value lives inside the variable itself. A class is a **reference type** — the variable holds a handle, and the object lives on the heap. That difference decides what assignment does, what pass-to-function does, and where memory allocations happen.

This lesson shows a Point struct being copied by assignment versus a Point class being shared, so you can see why the same code with one keyword changed can behave completely differently.

Stack

value types live here in full
Main()
aPointS
X = 1

int, double, bool, DateTime and every struct you write work this way.

Step 1 of 6. A struct variable holds the data itself. `PointS a` is not a reference to anything. The `int X` lives directly inside `a`'s slot on the stack. There is no heap allocation and no indirection — the variable *is* the value.

01 / 06

Step 01 / 06

A struct variable holds the data itself

PointS a is not a reference to anything. The int X lives directly inside a's slot on the stack.

There is no heap allocation and no indirection — the variable *is* the value.

Program.csC#
struct PointS { public int X; }      // value typeclass  PointC { public int X; }      // reference typestatic void Mutate(PointS s, PointC c) {    s.X = 99;   // changes a copy    c.X = 99;   // changes the caller's object}static void Main() {    PointS a = new PointS { X = 1 };    PointS b = a;          // full copy    b.X = 42;              // a.X is still 1    PointC p = new PointC { X = 1 };    PointC q = p;          // copies the reference    q.X = 42;              // p.X is now 42 too    Mutate(a, p);}