C# and .NET • Modern C# baseline
Classes, Objects, and Encapsulation
Use classes when behavior and protected state belong together.
A class defines a reference type; each instance has identity and can be shared through references. Encapsulation protects invariants by keeping state private and exposing meaningful operations. Not every data shape needs a class—structs and records can be better for value-like data.
Key points
- Private fields protect invariants from arbitrary callers.
- Avoid public mutable fields in application models.
Example
class Counter
{
private int _value;
public int Value => _value;
public void Increment()
{
_value++;
}
}
What to expect
Callers can increment the counter and read its value, but cannot assign the private field directly.
Practice exercise
Add a method to reset the counter and decide whether negative values should be possible.
Key idea: Expose domain operations rather than unrestricted access to internal state.