Classes: The Blueprint

Classes: The Blueprint in C#: A blueprint is not a house. You cannot live in it, it has no address, and drawing a second copy of it does not give anyone…

The Analogy: The Architect's Drawing

A blueprint is not a house. You cannot live in it, it has no address, and drawing a second copy of it does not give anyone somewhere to sleep. What it gives you is a specification: three bedrooms here, load-bearing wall there, and a rule that the front door must be lockable.

A class is that drawing. new is the building contractor: it takes the drawing, pours concrete on the heap, and hands you back the address of the finished house. Ten new calls give you ten houses from one drawing, each with its own furniture and its own state.

Two consequences of the analogy matter immediately. First, because what you hold is an address rather than the house, giving a friend your address does not build them a second house — they walk into yours. Second, because the drawing specifies the walls, it can also specify which doors the public may use and which are staff-only. That is encapsulation, and it is the whole reason classes beat loose bags of variables.


Syntax or Core Structure

using System;

class BankAccount
{
    private decimal balance;                       // state: nobody else may touch it
    private readonly string owner;                 // set once, in the constructor
    public static int OpenAccounts { get; private set; }   // shared by all accounts

    public BankAccount(string owner, decimal opening)
    {
        if (opening < 0m)
            throw new ArgumentOutOfRangeException(nameof(opening), opening, "cannot be negative");

        this.owner = owner;                        // this. disambiguates field from parameter
        balance = opening;
        OpenAccounts++;
    }

    public BankAccount(string owner) : this(owner, 0m) { }   // chains to the one above

    public decimal Balance => balance;             // read-only window onto the state

    public void Deposit(decimal amount)
    {
        if (amount <= 0m)
            throw new ArgumentOutOfRangeException(nameof(amount), amount, "must be positive");
        balance += amount;
    }

    public bool TryWithdraw(decimal amount)
    {
        if (amount <= 0m || amount > balance) return false;
        balance -= amount;
        return true;
    }

    public override string ToString() => $"{owner}: {balance:F2}";
}

class Program
{
    static void Main()
    {
        var ada = new BankAccount("Ada", 120m);
        var grace = new BankAccount("Grace");      // second constructor, opens at zero

        ada.Deposit(30m);
        Console.WriteLine($"withdraw 200: {ada.TryWithdraw(200m)}");
        Console.WriteLine($"withdraw 50:  {ada.TryWithdraw(50m)}");
        grace.Deposit(75.5m);

        Console.WriteLine(ada);                    // ToString is called for you
        Console.WriteLine(grace);
        Console.WriteLine($"open accounts: {BankAccount.OpenAccounts}");

        BankAccount alias = ada;                   // one object, two names
        alias.Deposit(10m);
        Console.WriteLine($"ada after alias deposit: {ada.Balance:F2}");
        Console.WriteLine($"same object: {ReferenceEquals(ada, alias)}");
    }
}

Output:

withdraw 200: False
withdraw 50:  True
Ada: 100.00
Grace: 75.50
open accounts: 2
ada after alias deposit: 110.00
same object: True

The last two lines are the reference-semantics point made concrete: alias was never a copy of the account, only a second label on it, so a deposit through one name is visible through the other.


Technical Depth: Members, Access, and the Rules Nobody Tells You

A class body may contain fields, constructors, properties, methods, events, indexers, nested types and a finaliser. Fields hold the state; everything else exists to control how that state is reached.

Access modifiers

ModifierVisible to
privatethis class only — the default for fields, and the right default
publiceveryone, everywhere
protectedthis class and anything deriving from it
internaleverything in the same assembly — the default for the class itself
protected internalthe same assembly, or any derived class anywhere
private protectedderived classes, but only those in the same assembly

Note the two defaults. An undecorated class is internal, so it vanishes when someone references your library; an undecorated field is private. Both are sensible, and both are frequently a surprise.

Constructors

If you write no constructor, C# supplies a public parameterless one. The moment you write any constructor, that gift is withdrawn — which is why adding BankAccount(string, decimal) to a class that was being created with new BankAccount() breaks every caller. Add the parameterless overload back explicitly if you still need it.

Constructors chain with : this(...), and the chained one runs first. A static constructor is different again: it takes no parameters, no access modifier, and the runtime runs it exactly once before the type is first used.

class Config
{
    public static readonly string MachineName;
    static Config() => MachineName = Environment.MachineName;   // runs once, on first use
}

C# 12 adds primary constructors, which fold the parameters into the class header:

class Point(double x, double y)
{
    public double Length => Math.Sqrt(x * x + y * y);   // x and y are in scope everywhere
}

Object initialisers versus constructors

var a = new BankAccount("Ada", 120m);          // invariants enforced
var b = new Person { Name = "Ada", Age = 36 }; // just a sequence of assignments

An object initialiser is sugar for "construct, then assign each property". It therefore cannot enforce anything: the object exists in an incomplete state between the two steps, and nothing forces the caller to set Name at all. Use constructor parameters for values the object cannot be valid without, and initialisers for genuinely optional extras. required (C# 11) closes the gap when you want initialiser syntax with compile-time enforcement.

What you inherit whether you ask or not

Every class derives from object and so arrives with four members already in place:

MemberDefault behaviourOverride when
ToString()prints the type namealmost always, for logs and debugging
Equals(object)reference identitytwo distinct objects should count as equal
GetHashCode()derived from identityyou overrode Equals — always both, never one
GetType()the runtime typenever; it is not virtual

Because Equals defaults to identity, new Point(1, 2) == new Point(1, 2) is false for a class. If value equality is what you want, a record gives you all four correctly for free — which is the subject of a later lesson.

static, sealed, and partial

static members belong to the type, not to any instance, so OpenAccounts above is one counter shared by every account. A static class cannot be instantiated at all and is the right home for stateless helpers. sealed forbids inheritance and lets the JIT devirtualise calls. partial splits one class across several files, which is how designer-generated and hand-written code coexist.


Real World Example: A Shopping Cart That Cannot Be Corrupted

The point of a class is not that it groups data — a tuple does that. The point is that it can guarantee something. This cart guarantees three invariants no caller can break: quantities are always positive, the same SKU never appears on two lines, and shipping is always consistent with the subtotal.

using System;
using System.Collections.Generic;

class Cart
{
    private class Line                      // nested and private: an implementation detail
    {
        public string Sku = "";
        public int Qty;
        public decimal UnitPrice;
        public decimal Total => Qty * UnitPrice;
    }

    private const decimal FreeShippingFrom = 50m;
    private const decimal Shipping = 4.99m;

    private readonly List<Line> lines = new();

    public int Count => lines.Count;

    public decimal Subtotal
    {
        get
        {
            decimal sum = 0m;
            foreach (Line l in lines) sum += l.Total;
            return sum;
        }
    }

    public decimal ShippingCost =>
        Count == 0 || Subtotal >= FreeShippingFrom ? 0m : Shipping;

    public decimal Total => Subtotal + ShippingCost;

    public void Add(string sku, int qty, decimal unitPrice)
    {
        if (qty <= 0)
            throw new ArgumentOutOfRangeException(nameof(qty), qty, "must be positive");

        Line? existing = lines.Find(l => l.Sku == sku);
        if (existing is null)
            lines.Add(new Line { Sku = sku, Qty = qty, UnitPrice = unitPrice });
        else
            existing.Qty += qty;            // merge, so a SKU can never appear twice
    }

    public bool Remove(string sku) => lines.RemoveAll(l => l.Sku == sku) > 0;

    public void Print()
    {
        foreach (Line l in lines)
            Console.WriteLine($"  {l.Sku,-10}{l.Qty,3} x {l.UnitPrice,6:F2} = {l.Total,7:F2}");

        Console.WriteLine($"  {"subtotal",-10}{Subtotal,22:F2}");
        Console.WriteLine($"  {"shipping",-10}{ShippingCost,22:F2}");
        Console.WriteLine($"  {"total",-10}{Total,22:F2}");
    }
}

class Program
{
    static void Main()
    {
        var cart = new Cart();
        cart.Add("mug", 2, 7.50m);
        cart.Add("tee", 1, 18.00m);
        cart.Add("mug", 1, 7.50m);          // merges into the existing mug line

        Console.WriteLine($"lines {cart.Count}");
        cart.Print();

        Console.WriteLine($"removed tee: {cart.Remove("tee")}");
        Console.WriteLine($"removed hat: {cart.Remove("hat")}");
        cart.Print();
    }
}

Output:

lines 2
  mug         3 x   7.50 =   22.50
  tee         1 x  18.00 =   18.00
  subtotal                   40.50
  shipping                    4.99
  total                       45.49
removed tee: True
removed hat: False
  mug         3 x   7.50 =   22.50
  subtotal                   22.50
  shipping                    4.99
  total                       27.49

Look at what the caller cannot do. It cannot reach lines, so it cannot add a negative quantity or a duplicate SKU. It cannot set Subtotal, because the subtotal is not stored — it is computed on demand from the only copy of the truth, which is why it can never drift out of step with the lines. And ShippingCost is derived the same way, so "free over fifty" is enforced in exactly one place.

The Line class is nested and private, which is a deliberate choice: it is a detail of how Cart keeps its books, and making it visible would let callers hold a Line and mutate Qty behind the cart's back. Note too that lines is readonly — the list it points at is mutable, but nothing can swap in a different list, which is the guarantee that keeps Count and Subtotal talking about the same data.


Common Mistakes

  1. Expecting assignment to copy the object. var b = a; gives a second name for one object, not a second object — every mutation through b is visible through a.
  2. Making fields public "for convenience", then discovering there is nowhere left to put a validation rule. Keep fields private and expose properties.
  3. Adding a parameterised constructor and breaking every new Thing() call site, because writing one constructor removes the implicit parameterless one.
  4. Comparing two class instances with == and expecting value equality. Without an override it is reference identity, so two identical-looking objects are unequal.
  5. Overriding Equals without GetHashCode. The object then behaves correctly in an if and incorrectly in a Dictionary or HashSet.
  6. Using an object initialiser for values the object cannot be valid without, leaving a window where the object exists half-built.
  7. Storing a value that could be computed — a subtotal field alongside the lines — and then having to remember to update it in five places.
  8. Calling a method on a null reference and blaming the method. NullReferenceException means the variable never pointed at an object; enable nullable reference types and the compiler will tell you where.

Best Practices

  • Keep every field private, and expose only what callers genuinely need through properties or methods.
  • Enforce invariants in the constructor and throw ArgumentException-family exceptions with nameof so bad objects cannot exist at all.
  • Mark fields readonly when they are set once; it documents intent and the compiler enforces it.
  • Compute derived values in a property rather than storing them, unless profiling shows the recomputation matters.
  • Override ToString() on anything you will ever log or debug — it costs one line and saves hours.
  • Prefer a record when the type is a bag of values compared by content, and a class when it owns behaviour and mutable state.
  • Give the type one job. A class that both prices an order and emails the customer has two reasons to change and no clear name.
  • Nest and privatise helper types that exist only to serve the outer class, so they cannot be handed to callers by accident.

Practice Exercises

  1. Write a Thermostat class with a private current temperature, a constructor taking a target between 5 and 30 (throwing ArgumentOutOfRangeException otherwise), a Nudge(double delta) method that clamps the result to the same range, and an overridden ToString(). Drive it from Main with five nudges, printing after each, including one that would exceed the range.
  2. Build a Deck class holding a private string[52] and a static readonly Random shared by all decks. Give it Shuffle(), Deal(int n) returning a string[], and a Remaining property, then deal three hands and print how many cards are left after each. Make Deal throw when asked for more cards than remain.
  3. Create a Stopwatch-style Timer class with two constructors — one parameterless and one taking a label — chained with : this(...). Add a static int Created counter, create four timers, and print the counter plus each timer's label to show which constructor ran.
  4. Take the Cart above and add a Coupon feature: a private decimal discountRate set only through ApplyCoupon(string code), which accepts "SAVE10" and "SAVE20" and returns false for anything else. Make Total include the discount, prove that applying an unknown code changes nothing, and explain in two sentences why discountRate must not be public.