C# and .NET • Modern C# baseline
Properties, Constructors, and Object Invariants
Establish valid object state during construction and expose controlled access through properties.
Properties look like fields to callers but can validate or compute values. Constructors should establish the object’s required invariants before it is used. C# primary constructors and object initializers are convenient, but validation still belongs at a clear boundary.
Key points
- Use init-only properties for data that is set during initialization.
- Do not let partially initialized objects escape from constructors.
Example
class Percentage
{
public int Value { get; }
public Percentage(int value)
{
if (value is < 0 or > 100)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
Value = value;
}
}
What to expect
A Percentage instance can only hold a value from 0 to 100.
Practice exercise
Add a property for a label that cannot be blank and explain how validation is performed.
Key idea: Enforce invariants once at construction instead of relying on every caller to remember them.