Glossary / Properties
Properties
A property is a member that exposes data through accessor methods, usually get, set, or init, while presenting field-like syntax to callers. Properties can enforce validation, compute values, preserve invariants, and control mutability; they are not fields and access may execute arbitrary code.
Auto and custom properties
public decimal Balance { get; private set; }
public string Name { get; init; }
public bool IsEmpty => Count == 0;
An auto-property has compiler-generated backing storage. A custom property can implement accessors with logic. init restricts assignment to initialization contexts; it does not make referenced values immutable. Expression-bodied properties are concise for computed values, but expensive or side-effectful getters are surprising because callers expect property access to be cheap and stable.
Properties can be virtual, abstract, static, required, nullable, or explicitly implemented. Accessor accessibility can differ (public get; private set;). Changing a public field to a property is source-compatible in many cases but can break binary compatibility and reflection/serialization assumptions.
Design guidance
Validate setters or use methods when transitions need meaningful errors. Keep getters side-effect-free and avoid I/O. Use immutable/init properties for construction-time state, but consider deep immutability. Make accessors as restrictive as possible and document computed costs where unavoidable.
Interview questions
- Property vs field? A property uses accessor methods and can encapsulate behavior; a field is storage.
- What does
initguarantee? Assignment only during allowed initialization, not deep immutability. - Should getters perform I/O? Generally no; property syntax suggests cheap, side-effect-free access.
- Can properties be virtual? Yes, except restrictions for certain property forms; virtual dispatch applies to accessors.
- Why can field-to-property break binaries? Compiled callers and reflection may bind to different metadata/member shapes.