C# / CHAPTER 07

Classes, properties, and invariants

Intermediate

Model state with controlled updates and clear object identity.

By the end of this chapter

  • Initialize private state
  • Expose a controlled property
  • Trace aliases to one object

The idea

A class groups state with operations that maintain it. Properties offer field-like access syntax while allowing the class to control reading and writing. A property with a private setter can be updated by the class but not freely assigned by callers. Constructors establish a valid starting state, and methods preserve the conditions that define a valid object.

Class variables hold references. Assigning one to another copies the reference, not the object, so both names can observe the same mutation. Do not assume every C# type behaves this way: structs have value semantics. Decide whether your model requires shared identity or independent values before choosing its representation.

C# example
using System;
var meter = new Meter();
var alias = meter;
alias.Add(3);
Console.WriteLine(meter.Value);
class Meter {
  public int Value { get; private set; }
  public void Add(int amount) {
    if (amount < 0) throw new ArgumentOutOfRangeException(nameof(amount));
    Value += amount;
  }
}
Result
3

meter and alias refer to the same Meter instance. Its public method validates the update, while the private setter prevents direct external assignment.

Try it yourself

Design a ScoreBoard whose Reset and Add methods are the only ways to change its score.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

With Meter above, which statement is allowed from ordinary caller code?