Skip to main content
CodeOath
← All posts

C#64 min total · 17 parts

C# Fundamentals: Value Types, Reference Types, Boxing, and the Type System

Part 1 of 17 · ~2 min

Overview

Ask a room of C# developers to state the rule and you'll get it right almost every time: value types copy, reference types share. Ask the same room to predict what six lines of real code print, and the room splits. Knowing the rule and reliably applying it turn out to be two different skills, and the gap between them is where boxing surprises, mutated-struct bugs, and "why didn't my change stick" bug reports actually live.

So instead of one fresh snippet per mechanism, this reference builds one thing, start to finish: the pick-station code behind a small warehouse — the part that scans an item off a shelf, decides how much stock is left, and adds it to the order being packed. Structs and classes, both representing warehouse data, get pushed through every mechanism below in the order you'd actually hit them.

Here's the first version, before any of that:

class PickStation
{
    public Dictionary<string, int> OnHand = new();

    public void Scan(string sku, int qty)
    {
        OnHand[sku] -= qty;
        if (OnHand[sku] < 0)
            Console.WriteLine("oversold: " + sku);
    }
}

Eleven lines, and it's already wrong in ways that won't show up until the warehouse actually gets busy. There's no shipment being assembled anywhere — scanning an item just decrements a number and maybe prints a warning, with no record of which order it belongs to. There's no audit trail of who adjusted what stock count or when, which is the first thing an ops manager asks for the moment a count looks wrong. Every SKU shares one dictionary with no history, so there's no way to answer "what did we have on hand an hour ago." And it silently trusts every caller to pass a real sku and a sane qty — nothing here can express "we haven't counted this SKU yet" as anything other than a number that might be zero for the wrong reason.

By the last chapter, this same system tracks a point-in-time stock count as its own small piece of data, hands out non-destructive price adjustments without ever touching the original quote a customer already saw, survives being logged into an old audit system built years before generics existed, rejects an adjustment that would oversell instead of quietly going negative, and opens a real connection to the warehouse's barcode scanner hardware with a guarantee that the connection gets closed no matter what goes wrong while it's open.

Work through it top to bottom if you can — several chapters collect something an earlier one planted on purpose. If you're here for one topic, the sidebar drops you straight in; every chapter opens by naming which version of the system it's extending.