Object-oriented programming
The four classic OOP ideas are easiest to understand through the C# mechanisms that implement them.
Encapsulation
Encapsulation keeps internal state behind a deliberate API. Callers should not need to know every field or invariant inside an object.
Inheritance and polymorphism
Inheritance models an is-a relationship. A derived class can reuse and specialize a base class. Runtime polymorphism lets code written against a base type execute behavior supplied by a derived runtime object.
public abstract class Reporter
{
public abstract string BuildReport();
}
public sealed class JsonReporter : Reporter
{
public override string BuildReport() => "{ \"status\": \"ok\" }";
}
Reporter reporter = new JsonReporter();
Console.WriteLine(reporter.BuildReport());The variable is typed as Reporter, but virtual dispatch calls the JsonReporter implementation.
Abstraction
Abstraction exposes the essential contract while hiding implementation details. C# commonly expresses abstraction through interfaces and abstract classes. abstract members have no concrete base implementation; sealed can prevent further inheritance or overriding.
Key points
- Encapsulation protects state and invariants behind an API.
- Inheritance is best for real is-a relationships; composition often fits has-a relationships better.
virtual/overrideand abstract members enable runtime polymorphism.- Method hiding with
newis not the same mechanism as overriding.