Skip to main content
CodeOath

Chapter 1 · About 12 minFree

Values, references and strings

Learn how C sharp copies and shares data: value and reference types, immutable strings, and the three meanings of equality, each shown in a small run.

Published by Hem Mankad, founder of CodeOath and a software engineer for more than eight years. Prepared with AI assistance.

Why a .NET backend starts with the type system

Paperlark's stock service keeps track of how many of each product are on the shelf, and it will become a web API in a few chapters. Before any of that, one question decides whether the code behaves the way you think: when you hand a piece of data to another variable or another method, do you hand over a copy or the thing itself? C# answers differently for different types, and many bugs, from a count that "did not save" to a dictionary that cannot find what is in it, come from not knowing which answer applies.

Everything below was run, in C# on .NET 10.0 with the Release configuration, on one machine. To repeat any experiment yourself you do not need a project: the .NET 10 SDK runs a single C# file directly with dotnet run -c Release file.cs, where the statements come first and the type declarations after them. The first run on a clean machine is slow (it took 38 seconds here, including restoring and compiling), later runs a few seconds. Where a number is shown it is the output of that run, and numbers about time will differ on yours; the shape of the result is what matters.

Value types copy, reference types share

A struct is a value type, like int and DateTime. A class is a reference type. The rule in one line: assigning a value type copies the data, and assigning a reference type copies a reference to the same object.

struct StockCount { public string Sku; public int OnHand; }
class Shipment { public string OrderId = ""; public List<string> PickedSkus = new(); }

var counted = new StockCount { Sku = "PEN-01", OnHand = 42 };
var forReport = counted;
forReport.OnHand = 0;
// counted=42 forReport=0

forReport got its own copy the moment of the assignment, so zeroing it left counted at 42. Now the same idea with a class:

var shipment = new Shipment { OrderId = "ORD-9001" };
var also = shipment;
also.PickedSkus.Add("PEN-01");
// shipment.PickedSkus.Count is 1, and ReferenceEquals(shipment, also) is True

There was only ever one Shipment. The two variables are two names for it, so a change made through either is visible through both. That is often what you want: the picker's scanner and the packer's screen should see the same shipment as it fills.

Passing an argument to a method is an assignment too, so the same rule applies, and this is where most surprises hide:

static void ZeroOut(StockCount c) { c.OnHand = 0; }
static void MarkPacked(Shipment s) { s.PickedSkus.Add("PACKED"); }
static void Replace(Shipment s) { s = new Shipment { OrderId = "DECOY" }; }

After ZeroOut(live) the caller's count was still 42, because the method changed its own copy. After MarkPacked(shipment) the shipment had 2 picked items, because the method changed the shared object. After Replace(shipment) its order id was still ORD-9001: Replace pointed its own parameter at a new object, which the caller never sees. Keep two verbs apart. Mutating the object a reference points to is visible to everyone who holds that reference. Reassigning the variable that holds the reference is local to that variable.

Shallow copies and default values

Copying a struct copies its fields, and a field that holds a reference copies only the reference. Take a struct Pick with a Sku string and a Notes list. After var copy = original;, changing copy.Sku to NB-07 left original.Sku as PEN-01, as expected. But copy.Notes.Add("gift wrap") changed the original too: original.Notes printed fragile, gift wrap, and ReferenceEquals(original.Notes, copy.Notes) was True. The copy is shallow. A struct that contains a list is not isolated from its copies; if you need an independent copy, you have to copy the list yourself.

The other everyday difference is what a variable holds before anything is assigned. A struct always has a value: default(Pick) has a null Sku and a null Notes, and new Pick[2] gives two usable structs whose Sku is null. A reference-type variable can hold nothing at all, and using it fails at run time with NullReferenceException: Object reference not set to an instance of an object. That is the message to expect when a class variable was never assigned, and the nullable reference annotations in recent C# exist to warn about it before the code runs.

The stack and heap misconception

The usual shorthand is "value types live on the stack, reference types on the heap". It is close, and wrong in a way that matters. The real question is where the variable sits, and that is independent of the copy-or-share question.

The runtime can count the bytes it allocates on the managed heap, which makes the difference visible. In the run, a loop that created 1,000 StockCount structs as local variables allocated 0 bytes. A loop that created 1,000 instances of the same type written as a class allocated 32,000 bytes: 32 bytes per object, each with its own header on the heap. An array of 1,000 structs took 16,024 bytes in one block, with the data inside it. An array of 1,000 class references took 8,024 bytes while empty and 40,024 once the objects were created, because the array holds only references and every object is a separate allocation.

Now put the same struct in a field of a class. A holder object with an id and a StockCount field allocated 40 bytes; the same holder without the struct field allocated 24. The struct did not get a stack slot of its own: it went into the heap object, 16 bytes inline. So a value type can live on the heap, inside something else. A variable a lambda captures, or one still needed after an await, also moves to the heap because it must outlive the call that declared it.

The two questions come apart outside the plain local variable. "Where is the memory?" depends on the variable. "What does assignment do?" depends on the type. For a local int they happen to line up, which is why the shorthand feels true until it gives a wrong prediction.

Strings: immutable reference types

string is a reference type with one rule that makes it feel like a value: it can never be changed in place. Every operation that seems to edit a string builds a new one.

string sku = "PEN-01";
string label = sku;
label += "-DISCONTINUED";
// sku=PEN-01 label=PEN-01-DISCONTINUED

sku was unaffected because += made a new string and pointed label at it. The same fact explains a common dead statement. Calling padded.Trim(); on its own line leaves padded as PEN-01 , still with its spaces; the trimmed value is only kept if you use the result (padded.Trim() returned PEN-01). The method produced a new string and nobody took it.

Immutability has a benefit: a string cannot be caught half-edited, so it can be a dictionary key and be shared between threads without a lock. It has a cost when you build a long string one piece at a time. Each += allocates a new string and copies everything so far.

string manifest = "";
foreach (var s in skus) manifest += s + "\n";           // new string every time

var sb = new StringBuilder();
foreach (var s in skus) sb.AppendLine(s);                // one growable buffer
string manifest2 = sb.ToString();

Measured on the same lines, with 400 SKUs the += loop allocated 1,614,400 bytes and the StringBuilder 25,928, both finishing in a couple of milliseconds, which nobody would notice. With 20,000 SKUs the += loop allocated 4,000,720,000 bytes and took 1,084.6 ms, and the StringBuilder allocated 891,072 bytes and took 4.9 ms. The cost grows with the square of the length, so it hides in small tests and appears with real data. A loop that builds a string is the signal to use a StringBuilder; a handful of concatenations in one expression is fine.

Comparing strings has one more trap, and it matters for any backend that handles user input. ToLower() and the culture-aware comparisons use the current culture, and cultures disagree. "TITLE".ToLower() gave title in en-US and tıtle in tr-TR, with a dotless i, so a lookup key lowered on a Turkish machine no longer matches the same key lowered on a server set to US English. With the current culture set to tr-TR, string.Equals("FILE", "file", StringComparison.CurrentCultureIgnoreCase) was False and OrdinalIgnoreCase was True. For identifiers, SKUs, paths and keys, say which comparison you mean: use StringComparison.Ordinal or OrdinalIgnoreCase, ToLowerInvariant(), or a dictionary built with StringComparer.OrdinalIgnoreCase. A Dictionary<string,int> created with that comparer found PEN-01 when Pen-01 was stored (True), and the default dictionary did not (False).

Strings that are written as literals in source are also shared: two literals "PEN-01" were the same object (True). A string built at run time from the same characters was a different object (False) until string.Intern returned the shared one (True). Do not rely on that for correctness; it is a reason why == on strings is defined by content, not identity.

Value equality and reference equality

== does not mean one thing. What it checks depends on the type on either side.

For int, it compares the data (5 == 5 is True). For a class that defines nothing, it compares identity: two Shipment objects created with the same order id compared False with == and False with Equals. That is a good default for something with a real identity, because two shipments are not the same shipment just because an id was typed twice. string is the built-in reference type that overloads == to compare characters: two strings built separately from the same characters were == (True) but ReferenceEquals said False, so they were two objects with equal content. A struct inherits value-based equality: two StockCount values with the same fields gave Equals True without any code written.

Two traps sit close to that last point. The first is speed. The inherited comparison for a struct that holds a reference field such as a string goes through a slow path. Two million Equals calls on the StockCount struct took 389 ms; the same struct with a hand-written Equals took 2 ms; and a struct of just two int fields, which has a quick path, took 45 ms. A loop can optimise numbers like these, so read them as a direction, and the direction is clear: for a struct used in hot code, write IEquatable<T> yourself, or use a record struct, which does it for you.

The second trap is silent. If a class overrides Equals and not GetHashCode, nothing fails to compile. Two ShipmentRequest objects with the same SKU and quantity gave Equals True, but HashSet.Contains for the twin returned False, and a set into which both twins were added held 2 items. The set uses GetHashCode to choose a bucket and only then calls Equals, and the default hash is per object. With GetHashCode overridden as HashCode.Combine(Sku, Quantity), Contains returned True and the set held 1. The rule is simple and absolute: override the two together.

Choosing between a struct and a class

Now that both behaviours are visible, the choice has a rule of thumb. Pick a struct for a small piece of data that is one logical value, that you will not change after creating it, and that is created in large numbers or lives briefly: a price, a coordinate, a stock count. Pick a class for something with an identity, such as a shipment or an order, or something that changes over its life, or something large.

Size is part of it, because a struct is copied on every assignment and every call. The runtime reported StockCount (a string reference and an int) as 16 bytes, decimal as 16, DateTime as 8, and a struct of six decimals as 96 bytes. Copying 16 bytes is cheap; copying 96 on every call to a method is not, and the Microsoft design guidance, from its documentation, suggests keeping a struct under about 16 bytes. The numbers also show why the same data in a class costs an extra header and a reference but is passed around as a single 8-byte reference.

If you are unsure, use a class. A class is never wrong in the way a large or mutable struct can be, and chapter 3 shows what goes wrong with mutable structs.

Mistakes that recur

  • Expecting a method to change a struct you passed. It changed its own copy; return the new value or pass it by reference (a later chapter).
  • Confusing mutate with reassign. Changing the object is shared; pointing a parameter somewhere else is local.
  • Believing "value types live on the stack". The variable decides, and a struct in a class field is on the heap.
  • Calling Trim() or Replace() and discarding the result. Strings do not change; use the returned value.
  • Lowering or comparing identifiers with the current culture. Use ordinal or invariant comparisons.
  • Using a large struct for convenience. It is copied on every call; keep structs small or use a class.
  • Assuming a copied struct is independent. Its reference fields still point at the same objects.
  • Building a long string with += in a loop. Use a StringBuilder.
  • Using == on classes and expecting content equality. It compares identity unless the type overloads it.
  • Overriding Equals without GetHashCode. Sets and dictionaries will not find the object.
  • Leaving a hot-path struct to inherited equality. Implement IEquatable<T>.

Carry forward, in short: assignment copies a value or copies a reference, and a method argument follows the same rule; the stack-and-heap story is about the variable, not the type; strings never change, so build long ones in a StringBuilder; and equality has three meanings that must be chosen on purpose, with Equals and GetHashCode always changed together. The next chapter builds on this with structs and records in more depth and with boxing, and chapter 3 adds the keywords that change how arguments travel: ref, out and in. Each of them will be run the same way, from a single file, so you can repeat it.

Coming: the guide answers questions in a later release.