Properties: The Security Guard

Properties: The Security Guard in C#: A public field is a hole in the wall. Anything can be pushed through it in either direction, and there is nowhere to…

The Analogy: The Guard on the Door

A public field is a hole in the wall. Anything can be pushed through it in either direction, and there is nowhere to stand and ask questions.

A property is that same doorway with a guard on it. From the outside it looks identical — you write p.Price = 24.99m exactly as you would to a field — but on the way in the guard can check the value, reject it, normalise it, log it, or fire an event. On the way out he can hand over something that was never stored at all, computing it on the spot.

The important part of the analogy is that the guard can be added later without redecorating the building. Callers do not change; the syntax at the call site is the same. That is the entire reason C# has properties rather than telling you to write GetPrice() and SetPrice(): you get the convenience of field syntax with the control of methods, and you can start with the convenience and add the control when you need it.


Syntax or Core Structure

using System;

class Product
{
    private decimal price;

    public string Name { get; init; } = "";      // set during construction, then frozen
    public int Stock { get; private set; }        // readable by all, writable in here only

    public decimal Price                         // full property with a validating setter
    {
        get => price;
        set
        {
            if (value < 0m)
                throw new ArgumentOutOfRangeException(nameof(Price), value, "cannot be negative");
            price = value;
        }
    }

    public decimal PriceWithVat => Math.Round(Price * 1.20m, 2);   // computed, stores nothing
    public bool InStock => Stock > 0;

    public static decimal VatRate { get; } = 0.20m;

    public void Restock(int qty) => Stock += qty;

    public bool TrySell(int qty)
    {
        if (qty <= 0 || qty > Stock) return false;
        Stock -= qty;
        return true;
    }
}

class Program
{
    static void Main()
    {
        var p = new Product { Name = "kettle", Price = 24.99m };
        p.Restock(3);

        Console.WriteLine($"{p.Name}: {p.Price:F2} (inc VAT {p.PriceWithVat:F2})");
        Console.WriteLine($"stock {p.Stock}, in stock {p.InStock}");
        Console.WriteLine($"sell 5: {p.TrySell(5)}");
        Console.WriteLine($"sell 2: {p.TrySell(2)}");
        Console.WriteLine($"stock {p.Stock}, in stock {p.InStock}");

        try { p.Price = -1m; }
        catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"rejected: {ex.ParamName}"); }

        Console.WriteLine($"price unchanged: {p.Price:F2}, vat rate {Product.VatRate * 100m:F0}%");
    }
}

Output:

kettle: 24.99 (inc VAT 29.99)
stock 3, in stock True
sell 5: False
sell 2: True
stock 1, in stock True
rejected: Price
price unchanged: 24.99, vat rate 20%

Four different property shapes appear there and all four read identically to the caller: an init-only one, one with an asymmetric private set, a full one with a hand-written setter, and two computed ones with no storage behind them at all.


Technical Depth: A Property Is Two Methods Wearing a Field's Clothes

The compiler turns public decimal Price { get; set; } into a private backing field plus two methods, get_Price() and set_Price(decimal). Everything that follows is a consequence of that.

public fieldproperty
Call-site syntaxp.Price = 5mp.Price = 5m — identical
Can validatenoyes, in the setter
Can be computednoyes, with no storage
Can be asymmetricnoyes, get; private set;
Allowed in an interfacenoyes
Usable with ref/outyesno
Works with data binding, serialisers, ORMsmostly noyes
Changing one breaks callersrecompile needed for binary compatno

Two rows there decide real designs. Properties cannot be passed as ref or out arguments, because there is no storage location to hand over — int.TryParse(s, out p.Count) will not compile, and you must parse into a local first. And interfaces can declare properties but never fields, so anything that will be abstracted behind an interface must expose properties from the start.

The accessor forms

public int A { get; set; }                  // auto: read and write
public int B { get; }                       // auto: set in the constructor only
public int C { get; init; }                 // auto: set in the constructor or an initialiser
public int D { get; private set; }          // read anywhere, write inside the class
public int E => a + b;                      // computed, no setter at all
public required string F { get; init; }     // C# 11: the caller must set it
public static int G { get; set; }           // one value shared by the type

init is the sweet spot for immutable-after-construction data: it permits object-initialiser syntax, then locks the property for good. required closes the last hole by making the compiler insist the initialiser sets it.

A property may also be virtual and overridden, and it may be an indexer when the "name" of the value is an argument:

public string this[int index] => rows[index];      // grid[3]

The recursion trap

public decimal Price
{
    get => Price;          // calls itself: StackOverflowException, uncatchable
    set => Price = value;  // same
}

A hand-written accessor must talk to the backing field, not to the property. The compiler will not stop you, the exception cannot be caught, and the process dies. Recent C# versions add a field keyword that names the compiler-generated backing field for you, removing the chance to get this wrong; until you are on that version, name the field yourself and keep it private.

Getters must stay cheap

Callers assume a property read is roughly free, and they will happily put one inside a loop condition. So:

public decimal Subtotal => lines.Sum(l => l.Total);   // fine: a handful of items
public Report FullReport => BuildFromDatabase();      // wrong: make this a method

If the work is slow, throws, has side effects, or returns something different each call, it is a method — the parentheses are a warning to the reader. DateTime.Now is the standard cautionary tale: it looks like a value and is actually a clock read, which is why two consecutive reads can disagree.

Auto-property initialisers versus the constructor

public List<string> Tags { get; } = new();     // runs before the constructor body

Initialisers run first, in declaration order, then the constructor body — so the constructor can override them but not vice versa. Prefer an initialiser for a plain default and the constructor for anything that depends on a parameter.


Real World Example: A Booking That Validates Itself

Hotel bookings are a good test of properties because half the interesting values are rules rather than data. Nights, total, deposit and long-stay status are all consequences of four stored values, and the two dates constrain each other.

using System;

class Booking
{
    private string guestName = "";
    private DateTime checkIn;
    private DateTime checkOut;
    private decimal ratePerNight;

    public string Reference { get; init; } = "";

    public string GuestName
    {
        get => guestName;
        set => guestName = string.IsNullOrWhiteSpace(value)
            ? throw new ArgumentException("guest name is required", nameof(GuestName))
            : value.Trim();                       // normalise on the way in
    }

    public DateTime CheckIn
    {
        get => checkIn;
        set
        {
            if (checkOut != default && value >= checkOut)
                throw new ArgumentException("check-in must precede check-out", nameof(CheckIn));
            checkIn = value.Date;
        }
    }

    public DateTime CheckOut
    {
        get => checkOut;
        set
        {
            if (value <= checkIn)
                throw new ArgumentException("check-out must follow check-in", nameof(CheckOut));
            checkOut = value.Date;
        }
    }

    public decimal RatePerNight
    {
        get => ratePerNight;
        set => ratePerNight = value >= 0m
            ? value
            : throw new ArgumentOutOfRangeException(nameof(RatePerNight), value, "cannot be negative");
    }

    public int Nights => (int)(CheckOut - CheckIn).TotalDays;
    public decimal Total => Nights * RatePerNight;
    public bool IsLongStay => Nights >= 7;
    public decimal Deposit => Math.Round(Total * (IsLongStay ? 0.20m : 0.50m), 2);

    public override string ToString() =>
        $"{Reference,-8}{GuestName,-8}{Nights,3} nights{Total,9:F2}{Deposit,9:F2}";
}

class Program
{
    static void Main()
    {
        var a = new Booking
        {
            Reference = "BK-1001",
            GuestName = "  Ada  ",
            CheckIn = new DateTime(2026, 4, 1),
            CheckOut = new DateTime(2026, 4, 4),
            RatePerNight = 89.50m,
        };

        var b = new Booking
        {
            Reference = "BK-1002",
            GuestName = "Grace",
            CheckIn = new DateTime(2026, 4, 10),
            CheckOut = new DateTime(2026, 4, 20),
            RatePerNight = 74.00m,
        };

        Console.WriteLine($"{"ref",-8}{"guest",-8}{"stay",10}{"total",9}{"deposit",9}");
        Console.WriteLine(a);
        Console.WriteLine(b);

        try { b.CheckOut = new DateTime(2026, 4, 5); }
        catch (ArgumentException ex)
        { Console.WriteLine($"rejected {ex.ParamName}: still {b.Nights} nights"); }

        try { a.RatePerNight = -10m; }
        catch (ArgumentOutOfRangeException ex)
        { Console.WriteLine($"rejected {ex.ParamName}: still {a.RatePerNight:F2}"); }

        Console.WriteLine($"guest name trimmed: '{a.GuestName}'");
        Console.WriteLine($"revenue {a.Total + b.Total:F2}, deposits {a.Deposit + b.Deposit:F2}");
    }
}

Output:

ref     guest         stay    total  deposit
BK-1001 Ada       3 nights   268.50   134.25
BK-1002 Grace    10 nights   740.00   148.00
rejected CheckOut: still 10 nights
rejected RatePerNight: still 89.50
guest name trimmed: 'Ada'
revenue 1008.50, deposits 282.25

Three property techniques are doing the work. GuestName normalises as well as validates, so " Ada " is stored trimmed and every later comparison behaves. The two date setters cross-check each other, with the checkOut != default guard so that setting CheckIn first in an object initialiser is legal. And because Nights, Total, IsLongStay and Deposit are all computed, a rejected write leaves every one of them consistent — there is no half-updated state to unwind, which is exactly what the two rejected lines demonstrate.

Reference is init-only: bookings may be re-dated and re-priced, but a reference that changed after the confirmation email went out would be a bug no validation could catch.


Common Mistakes

  1. Writing get => Price; inside the Price property. The accessor calls itself and the process dies with an uncatchable StackOverflowException; accessors must use the backing field.
  2. Exposing a public field because "it is only data", then having nowhere to add validation later without changing every call site's compiled form.
  3. Doing real work in a getter — a database call, a file read, an HTTP request. Callers assume reads are cheap and will put them in a loop.
  4. Storing a value that is derivable, such as a nights field beside two dates, and letting the two drift apart.
  5. Trying int.TryParse(text, out obj.Count). A property has no storage location, so it cannot be an out or ref argument; parse into a local and assign.
  6. Using { get; set; } everywhere by reflex, including on values that must never change after construction. init or a getter-only property says so and is enforced.
  7. Returning a mutable collection from a getter — public List<string> Tags { get; } — and being surprised when a caller calls .Clear() on your internals. Expose IReadOnlyList<T> instead.
  8. Validating in the constructor but not in the setter, so the object is born valid and can then be made invalid by one assignment.

Best Practices

  • Make properties, not public fields, even for plain data. It costs nothing today and buys every future option.
  • Choose the tightest accessor that works: get; for constants of the object, get; init; for construction-time data, get; private set; for state only the class may change.
  • Put the rule in the setter so it applies to every write, and repeat nothing in the constructor that the setter already checks.
  • Normalise in the setter — trim strings, take .Date off timestamps, upper-case codes — so the rest of the class can trust the field.
  • Derive rather than store. If two properties can disagree, one of them should not exist.
  • Keep getters cheap, side-effect-free and repeatable; if they cannot be, make it a method so the parentheses warn the reader.
  • Name a property for the value, not the action: Total, not GetTotal; IsLongStay, not CheckLongStay.
  • Throw ArgumentException or ArgumentOutOfRangeException from setters with nameof(Property), so the caller's log names the member that was rejected.

Practice Exercises

  1. Write a Rectangle class with Width and Height properties that reject values <= 0, plus computed Area, Perimeter and IsSquare. Set a valid size, print all three, then attempt Width = -4 in a try block and print the values again to prove nothing changed.
  2. Build a Student class with init-only Id and Name, a private List<int> grades, an AddGrade(int) method rejecting anything outside 0–100, and computed Average, Highest and Letter properties. Expose the grades as IReadOnlyList<int> and show that a caller cannot add to them directly.
  3. Create a Temperature class storing only Celsius, with computed Fahrenheit and Kelvin properties and a setter on Celsius that rejects anything below absolute zero. Add a second settable Fahrenheit property whose setter converts back into Celsius, then prove that setting either one keeps all three in agreement.
  4. Take the Booking class above and add a Guests property that rejects anything outside 1–4, plus a computed RequiresTwoRooms and a Total that adds 25.00 per night for a second room. Then deliberately introduce a stored nights field instead of the computed Nights, show a sequence of assignments that makes it wrong, and write two sentences on why the computed version cannot fail that way.