Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Programming Shortcut: C#

Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about value and reference semantics.

A big toolbox, and you need three tools

C# is a big language. Microsoft made it around 2000 for building large Windows programs, and it has been growing ever since. Today it runs servers, desktop apps, phone apps and a good share of the world’s video games. Every year it gains new features, and its documentation could keep you busy for a long winter.

You don’t need most of it. For this article you need three words, struct, class and record, plus the humble = sign.

Those three words carry a question that every programming language answers: when I copy this, what do I get? Do you get a second, independent thing, or a second name for the same thing?

Most languages pick one answer for you and leave you to discover it, usually by accident, usually at an inconvenient hour. C# hands you the choice, out loud, every time you define a type. That makes it the best place to learn what a variable actually holds. Once you’ve seen it here, you’ll spot it in every language you meet.

What carries over

You already know most of what a C# program is made of. Here is how a few familiar things are spelled:

What you knowluxC#
a variablevar count = 0var count = 0;
printingprint("hi")Console.WriteLine("hi");
an array[int]int[], or List<int> for one that grows
a recordstruct Point { x: int }struct, class or record: the subject of this article
a value that might be missingOption<int>int?

C# ends statements with semicolons and wraps blocks in braces. Loops, conditionals and functions look the way you’d guess. Read past them.

The fourth row is the interesting one. Where lux has one way to bundle named fields, C# has three. They look almost identical on the page, and they behave differently when you copy them.

Edit, save, watch it run

C# work runs through one command-line tool, dotnet, and it’s the only tool this article uses. The steps below are for Windows, because that’s where C# feels most at home. On Windows, one command installs it:

winget install Microsoft.DotNet.SDK.11

On macOS or Linux, follow Microsoft’s install guide; everything after this point is the same.

Make a new folder, and in it a file called app.cs with one line:

Console.WriteLine("Hello from C#");

Run it from a terminal in that folder:

dotnet run app.cs

The first run takes a few seconds while dotnet compiles your file, and then it prints Hello from C#. There’s no project file and no Main function to write. Statements at the top of the file run in order, the way a script would.

Now cut out the retyping:

dotnet watch run app.cs

dotnet watch runs your program, then waits. Every time you save the file, it compiles and runs it again. Leave it running in one window, keep your editor in another, and the rest of the article is three moves: edit, save, read the output. Press Ctrl+C when you’re done.

Copy it, change the copy

Here’s the experiment that this article is built on. Make a point, copy it, change the copy, and look at both:

var a = new Point { X = 1, Y = 2 };
var b = a;
b.X = 99;
Console.WriteLine($"a.X is {a.X}, b.X is {b.X}");

struct Point
{
    public int X;
    public int Y;
}

A few small things to read past: new Point { X = 1, Y = 2 } builds a point and sets its fields, public lets code outside the type see a field, and $"..." is a string with values dropped into the braces. In a file like this one, type definitions go after the statements that use them.

Save it, and the output reads a.X is 1, b.X is 99. Changing b left a alone. That’s probably what you expected. If you learned lux, it’s what lux always did: copy a struct and change the copy, and the original never noticed. In lux you never had to ask “is this a copy?” In C#, you have to ask.

Now change one word. Make struct Point into class Point, and save:

var a = new Point { X = 1, Y = 2 };
var b = a;
b.X = 99;
Console.WriteLine($"a.X is {a.X}, b.X is {b.X}");

class Point
{
    public int X;
    public int Y;
}

This time it prints a.X is 99, b.X is 99. You changed b, and a changed too. Same fields, same assignment, same line of output code. One word was different.

What’s in the box

Think of a variable as a labeled box. The question is what goes in the box.

A struct is a value type. The box holds the value itself: the X and the Y, right there inside the variable. int, double, bool and char are value types too. When you write var b = a, C# copies the contents of a’s box into b’s box. Now there are two points, and they have nothing to do with each other.

A class is a reference type. When you write new Point, C# builds the object somewhere else in memory, in an area the runtime manages for you called the heap, and hands you back a reference: a small value that says where the object lives. The box holds the reference, not the point. When you write var b = a, C# copies the contents of a’s box into b’s box, just as before. But the contents are a reference, so now two boxes refer to one point.

struct:   a [ X=1  Y=2 ]        b [ X=99 Y=2 ]       two points

class:    a [ ref ]──┐
                     ├──> { X=99 Y=2 }               one point
          b [ ref ]──┘

So here is the rule: assignment always copies the box, and the type decides what’s in the box. C# never quietly skips the copy. When the box holds a value, you get a second value. When it holds a reference, you get a second reference to the same object.

Two names for one object is called aliasing, and it’s neither good nor bad on its own. It’s how a program shares things. If three parts of your program need the same customer record, you want them all looking at one record, so that a change made by one is seen by all. If you meant to take a snapshot, aliasing is a bug.

How a reference is stored in the machine, and what a pointer really is, belong to the C article. For this one, “where the object lives” is enough.

Functions get a copy of the box too

Calling a function is an assignment in disguise. Each parameter is a new box, and the argument’s contents are copied into it. The same rule applies, so the same two outcomes follow:

var p = new Point { X = 1 };
Shift(p);
Console.WriteLine($"after Shift: {p.X}");
Replace(p);
Console.WriteLine($"after Replace: {p.X}");

void Shift(Point q)
{
    q.X += 10;
}

void Replace(Point q)
{
    q = new Point { X = 500 };
}

class Point
{
    public int X;
}

This prints after Shift: 11 and then after Replace: 11.

Shift got a copy of the reference, followed it to the one shared point, and changed it. The caller sees the change. Replace got a copy of the reference too, and then overwrote its own box with a reference to a brand-new point. That changed q, the function’s box, and never touched p, the caller’s box. The new point with 500 in it is dropped when the function ends.

Change class to struct and save. Now both lines print 1, because Shift changed its own private copy of the point.

This trips up programmers in every language that works this way, and most mainstream languages do. You can change the object a parameter refers to. You can’t change which object the caller’s variable refers to.

Unless you ask. C# has a keyword for handing a function the caller’s box itself instead of a copy of its contents:

var p = new Point { X = 1 };
Replace(ref p);
Console.WriteLine($"after Replace: {p.X}");

void Replace(ref Point q)
{
    q = new Point { X = 500 };
}

class Point
{
    public int X;
}

Now it prints 500. With ref, q is another name for the variable p, so writing to q writes to p. You have to say ref in both places, at the definition and at the call, so nobody gets surprised. Notice that this is a separate idea from reference types. A reference type puts a reference in the box. Passing by reference hands over the box. The words overlap, and the ideas don’t, which is why ref works on structs too.

Arrays and lists are references

Here’s where people coming from lux get caught. In C#, arrays are reference types, and so is List<T>:

int[] scores = [70, 85, 90];
var backup = scores;
backup[0] = 0;
Console.WriteLine($"scores[0] is {scores[0]}");

var copy = scores.ToArray();
copy[1] = 0;
Console.WriteLine($"scores[1] is {scores[1]}");

The first line prints scores[0] is 0. Naming your variable backup didn’t make it one. ToArray() builds a new array with the same contents, and changing that one leaves scores alone, so the second line prints scores[1] is 85.

What about a struct that contains an array or a list? Copying a struct copies its box, and only its box. A list field holds a reference, so the copy gets the reference, and both structs share one list:

var mine = new Hand { Owner = "me", Cards = ["ace"] };
var yours = mine;
yours.Owner = "you";
yours.Cards.Add("king");
Console.WriteLine($"{mine.Owner} holds {string.Join(", ", mine.Cards)}");

struct Hand
{
    public string Owner;
    public List<string> Cards;
}

This prints me holds ace, king. The owner was copied, so it stayed me. The list wasn’t copied, so the king turned up in both hands. A copy that copies only the top layer is called a shallow copy, and assignment in C# is always shallow. If you want the list copied too, you write that yourself.

Strings are a curious case. string is a reference type, yet you’ll never catch two string variables sharing a change. That’s because no C# string can be changed. name + "!" builds a new string and leaves the old one alone. When nothing can change an object, sharing it is harmless, and a reference to it behaves like a value. Hold on to that; it comes back in a moment.

What does “the same” mean?

Copying has a twin question: when are two things equal?

For a class, == asks whether two references point to the same object. It’s called reference equality, or identity. Two points with the same X and Y, made by two separate news, are not ==:

var a = new Point { X = 1 };
var b = new Point { X = 1 };
var c = a;
Console.WriteLine(a == b);
Console.WriteLine(a == c);

class Point
{
    public int X;
}

That prints False, then True: a and c are two boxes holding one reference. For a struct, the natural question would be whether the fields match, but C# won’t guess. A plain struct has no == at all until you write one:

var a = new Point { X = 1 };
var b = new Point { X = 1 };
Console.WriteLine(a == b);

struct Point
{
    public int X;
}

The compiler stops with error CS0019: operator == cannot be applied to two Points. (a.Equals(b) works, and compares the fields.)

This is where the third word, record, comes in. A record is a type the compiler fills with code that treats it as nothing but its data. You declare its fields in one line:

var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b);

var c = a with { X = 99 };
Console.WriteLine($"{a} and {c}");

record Point(int X, int Y);

That prints True, then Point { X = 1, Y = 2 } and Point { X = 99, Y = 2 }.

A record is a class, so a and b hold references to two separate objects. But the compiler wrote an == for it that compares the fields, which is called value equality. Its fields can’t be changed after it’s made, so instead of changing a, you write a with { X = 99 } and get a new record, a copy with one field different. a is still 1, 2.

Remember the strings? A record is the same trick: a reference type that nobody can change. It’s shared, and the sharing can’t hurt you, so it behaves like a value. There’s also record struct, a value type with the same conveniences, for when you want the box itself to hold the data.

So C# gives you four combinations, and you pick one each time you write a type:

You writeCopying gives you== asks
structa second, independent valuenothing, until you write it
classa second reference to the same object“same object?”
recorda second reference, but nobody can change the object“same fields?”
record structa second, independent value“same fields?”

The same question, everywhere

Here is what you can take to any language you meet: if I copy this and change the copy, what happens to the original? Every language has an answer, and now you know what to look for.

LanguageWhat a variable holds
luxalways a value; a copy is always yours
Calways a value; you make references by hand, as pointers (C)
Swiftthe same split as C#: structs are values, classes are references (Swift)
Gostructs and arrays are values; slices and maps share what they hold
Javanumbers, characters and booleans are values; every object is a reference
Pythonalways a reference; numbers and strings can’t change, so they act like values
JavaScriptnumbers and strings act like values; objects and arrays are references

Look at Python, Java and JavaScript. They never ask you to choose, and they all work like C#’s classes: pass an object to a function, and the function can change your object. When an experienced programmer in one of those languages says “be careful, that list is shared,” this is what they mean.

What a class gives up

lux made you a promise: whatever you copy is yours. Nobody else can change it. C#’s classes give that promise up. Any part of the program that holds a reference to your object can change it while you aren’t looking, and you’ll find out when you next read it. That’s the price of sharing, and in a large program it’s a real price: “who else has a reference to this?” can be a hard question to answer.

References bring one more thing lux didn’t have: a reference can point to nothing. That’s null, and it gets an article of its own (Java). C# warns you when a null might slip into a variable that shouldn’t hold one, and the ? in Point? says that one may.

Beware of changing a struct you can’t see. Structs get copied in places you don’t expect, and a change made to a copy disappears without a word. Put a struct in a List, and list[0] hands you a copy:

var counters = new List<Counter> { new Counter() };
counters[0].Add();
Console.WriteLine(counters[0].Count);

struct Counter
{
    public int Count;
    public void Add() => Count++;
}

This prints 0. Add ran, on a copy that vanished at the end of the line. The compiler does catch the plain case, counters[0].Count = 5, with error CS1612 (“Cannot modify the return value… because it is not a variable”), but it can’t see what a method does. My rule: change a struct only through a variable you named yourself, never through a list, a property or another object’s field. If that rule is hard to keep, declare a readonly struct, which the compiler refuses to change anywhere, and replace it instead of changing it. And when you can’t decide between struct and class, pick class or record. A struct suits something small that acts like a single value: a point, a color, an amount of money.

An undo that remembers

Undo is the classic place where value semantics matter. To undo, you keep a history of where you’ve been, and each entry in that history had better be a snapshot, not a second name for where you are now.

The project is one file, undo.cs, in projects/csharp/. A marker starts at (0,0) and follows a string of moves: N, S, E and W step one square, and u undoes the last step. Before each step, the current spot goes onto a stack (a list you add to and take from at the same end). Undo takes the top one back off.

Here is its heart:

history.Push(here);
switch (move)
{
    case 'N': here.Y += 1; break;
    case 'S': here.Y -= 1; break;
    case 'E': here.X += 1; break;
    case 'W': here.X -= 1; break;
}

And Spot is a struct with an X and a Y. Put the file in a folder of its own and start the watcher:

dotnet watch run undo.cs

It prints the spot and the history after every move:

N   at (0,1)   history: (0,0)
N   at (0,2)   history: (0,1) (0,0)
E   at (1,2)   history: (0,2) (0,1) (0,0)
u   at (0,2)   history: (0,1) (0,0)
E   at (1,2)   history: (0,2) (0,1) (0,0)
u   at (0,2)   history: (0,1) (0,0)
u   at (0,1)   history: (0,0)
S   at (0,0)   history: (0,1) (0,0)

Every undo steps back one square. Push(here) copied the spot into the stack, so when here moved on, the copy stayed put.

Now, with dotnet watch still running, change struct Spot to class Spot and save. The first four lines:

N   at (0,1)   history: (0,1)
N   at (0,2)   history: (0,2) (0,2)
E   at (1,2)   history: (1,2) (1,2) (1,2)
u   at (1,2)   history: (1,2) (1,2)

The history is full of the current spot, and undo does nothing. There was only ever one Spot object. Every Push(here) put another reference to it on the stack, and every move changed the one object they all refer to. The history was a list of aliases.

Before you change it back, open the file and read the “Try this next…” block at the bottom. It walks you through two ways to fix the class version, and one way the struct version can still share more than you’d think.

What this article leaves out

C# quietly converts a value type to a reference when you store it as a plain object, which is called boxing, and it has its own surprises. Where each kind of value lives in memory, and how the garbage collector clears away objects nobody refers to any more, got a sentence here and deserve more. in and out parameters, ref return values and Span<T> are refinements of the box idea for programs that care about speed. Inheritance and interfaces, the other half of what classes do, are another article’s subject (Swift teaches the interface idea). C# 15’s new union types, which combine existing types into one, are C#’s version of sum types, whose home is the Rust article.

When you want the full language, Microsoft’s C# documentation starts with a tour and works up. Its guide to choosing between class and struct is short and gives the same advice as the warning above. It dates from 2008, and it says “passed by reference” where this article would say “a copy of the reference is passed”, which you can now see is a different thing.

Ask the compiler what it wrote

You’ve seen that a record gets an == you never wrote. Ask the compiler what else it wrote. Make a new file with these two lines and run it:

foreach (var member in typeof(Cat).GetMembers()) Console.WriteLine(member);
record Cat(string Name);

You’ll find op_Equality (that’s the ==), an Equals, a Deconstruct and a method with the odd name <Clone>$. What is that clone for? Then change record to record struct, save, and look for it again. Why would a struct not need one?

  • C: what a reference really is in memory, and pointers you manage yourself.
  • Swift: structs as values on the way to protocols and generics.
  • Java: null, the reference that points to nothing.
  • Rust: sum types, the idea behind C# 15’s union.

Tested with .NET 11.0.100 and C# 15, November 2026.