Roadmap › OOP Concepts in C# › Module: The Four Pillars
Lessons in this course (15)

5. Encapsulation

Basic★ Must knowLesson 5 of 15

Encapsulation = keep data private and allow changes only through methods that enforce the rules (invariants).

csharp
// Bad: anyone can put the object in an invalid state
public class OrderBad { public List<OrderLine> Lines = new(); public decimal Total; }

// Good: the object protects its invariants
public class Order
{
    private readonly List<OrderLine> _lines = [];
    public IReadOnlyList<OrderLine> Lines => _lines;
    public decimal Total => _lines.Sum(l => l.Price * l.Qty);

    public void AddLine(Product p, int qty)
    {
        if (qty <= 0) throw new ArgumentException("Qty must be positive");
        _lines.Add(new OrderLine(p.Id, p.Price, qty));
    }
}

Benefits: validation in one place, freedom to change internals, fewer bugs.