DEV Community

DIVAKAR UPADHYAY
DIVAKAR UPADHYAY

Posted on Originally published at devladder.pages.dev

Encapsulation (OOP Concepts in C#)

👉 Read the full lesson on DevLadder (free, lesson 5 of 15 in the OOP Concepts in C# course)

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

// 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));
    }
}
Enter fullscreen mode Exit fullscreen mode

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

An interview question on OOP Concepts in C

Does C# support multiple inheritance?

Not for classes: a class has exactly one base class, which avoids the diamond problem (ambiguity when two parents implement the same member). A class can implement multiple interfaces. If two interfaces declare the same member, use explicit interface implementation to disambiguate.

Can you answer these?

  • What are access modifiers? What are the defaults?
  • What is the difference between method overriding and method hiding (new)?
  • What is the difference between composition and inheritance? Why "favour composition"?
  • Explain association, aggregation and composition with examples.

The answers, plus 11 more OOP Concepts in C# interview questions and a mock-interview mode, are free on DevLadder.

Next in the course: Abstraction →

Top comments (0)