Encapsulation & invariants
Hide internal state, expose safe operations, and keep class invariants true (e.g., non-negative balance, valid ranges).
Encapsulation overview
Goal: Protect your object’s state.
- Encapsulation: hide fields, expose safe APIs
- Invariant: a rule that is always true
- Validate in constructors/setters/methods
Read-only surface
Keep fields private. Give callers a read-only property and safe operations.
using System;
// Expose read-only view; mutate via methods only
public class Counter
{
private int _value; // hidden state
public int Value // read-only to callers
{
get { return _value; }
private set { _value = value; } // keep setter private
}
public void Increment()
{
Value = Value + 1;
}
}
public class Program
{
public static void Main(string[] args)
{
Counter c = new Counter();
c.Increment();
c.Increment();
Console.WriteLine("Value = " + c.Value);
}
}
All lessons in this course
- Fields, auto-properties, object initializers
- Constructors, static members
- Encapsulation & invariants