Lesson 14 of 24
In progress
Properties and encapsulation
Use auto-properties, computed properties and init accessors, and decide what should be settable from outside.
A property looks like a field and behaves like a method. That combination is why C# code exposes data with { get; set; } rather than public fields, and why the accessors deserve thought.
What you will learn
- Use auto-properties and computed properties.
- Restrict writes with
private setandinit. - Put validation where it cannot be bypassed.
Auto-properties
public class Customer
{
public int Id { get; init; }
public string Name { get; set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
}
{ get; set; } is an auto-property: the compiler creates a hidden backing field and the accessors. init allows a value only during construction or an object initialiser. private set allows the class to change it but not a caller.
The initialiser after = sets a default, which is why Name is never null even before anyone assigns it.
Computed properties
public class Order
{
private readonly List<decimal> lines = new();
public IReadOnlyList<decimal> Lines => lines;
public decimal Subtotal => lines.Sum();
public decimal Tax => Math.Round(Subtotal * 0.18m, 2);
public decimal Total => Subtotal + Tax;
}
A computed property has no setter and derives its value from other state. Total cannot disagree with Subtotal because it is not stored.
The cost is recomputation on every read. For a list of a few items that is irrelevant; for an expensive calculation over thousands, cache it and invalidate on change, and accept the extra complexity only when a measurement justifies it.
Validation in a setter
public class Product
{
private decimal price;
public decimal Price
{
get => price;
set
{
if (value < 0) throw new ArgumentOutOfRangeException(nameof(value));
price = Math.Round(value, 2);
}
}
}
A full property with a backing field allows logic in set. Here an invalid price is rejected and a valid one is rounded, so every read sees a consistent value.
The alternative — validate in the caller — spreads the rule across every call site and eventually misses one. Putting it in the property keeps it in one place.
init accessors
public class Invoice
{
public required string Number { get; init; }
public DateOnly Issued { get; init; } = DateOnly.FromDateTime(DateTime.Today);
}
init is the middle ground between a mutable property and a constructor parameter: the object can be created with an initialiser, then never changed. It pairs with required to make the compiler enforce the essential fields.
That combination is the modern replacement for a long constructor with many parameters, and it reads better at the call site because each value is named.
Expression-bodied accessors
public string Display => $"{Name} <{Email}>";
A read-only property is just a getter, so => is all it needs. Use get => ...; when the property also has a setter or a doc comment that requires a block.
Static properties
public static class Config
{
public static int PageSize { get; set; } = 20;
public static readonly string AppName = "Shop";
}
A static property is global state. It is convenient for configuration and awkward to test, because every test shares it. Prefer passing a settings object to the classes that need it, and keep static properties for values that genuinely do not change.
Indexers
public class Lookup
{
private readonly Dictionary<string, string> map = new();
public string this[string key]
{
get => map.TryGetValue(key, out var value) ? value : throw new KeyNotFoundException(key);
set => map[key] = value;
}
}
An indexer lets an object be used with lookup["x"]. It is worth writing when the type is genuinely a collection; otherwise a method name such as Get is clearer.
Properties versus methods
- A property should be cheap and free of side effects, like a field read.
- A method should be used when the work is expensive, can fail, or changes state.
A property that queries a database breaks the expectation set by every other property in the framework, and callers will put it in a loop. A method that only returns a field adds ceremony for nothing.
Interfaces with properties
public interface IPriced
{
decimal Price { get; }
}
An interface property can be read-only, which is a strong contract: implementations may compute it, but callers cannot set it. Prefer read-only members in interfaces unless mutation is part of the contract.
Adding a public setter to every property because it is easy. Each setter is a way to break an invariant; expose one only when changing that value is a legitimate operation the class supports.
Write a Rectangle class with width and height as validated properties, plus computed Area and Perimeter. Reject negative dimensions.
Show solution
public class Rectangle { private double width; private double height; public double Width { get => width; set => width = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value)); } public double Height { get => height; set => height = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value)); } public double Area => width * height; public double Perimeter => 2 * (width + height); } var r = new Rectangle { Width = 3, Height = 4 }; Console.WriteLine($"{r.Area} {r.Perimeter}"); Both setters reject negative values, so Area can never be negative. Area and Perimeter are computed rather than stored, so they cannot go stale after a dimension changes.
Recap
- Auto-properties for plain data, computed properties for derived values,
initfor immutable-after-construction. - Validation belongs in the setter or the constructor, not in every caller.
- Properties should be cheap and side-effect free; use a method when they cannot be.
Next, inheritance and polymorphism in C#: virtual, override and the base class rules.
Do auto-properties allocate a field?
Can a property throw?
Progress is saved in this browser only. No account, no email.