OOP concepts in C# with examples: classes, encapsulation, inheritance, polymorphism and abstraction
Object-oriented programming organises code around objects that combine data and the operations allowed on it. C# is built for this style, and the four principles usually listed, encapsulation, abstraction, inheritance and polymorphism, are easiest to understand on one small program that grows step by step. Ours models bank accounts.
Classes and objects
A class is a blueprint; an object is a concrete instance created with new. Each object has its own copy of the instance fields.
public class Account
{
public string Owner;
public decimal Balance;
}
var a = new Account { Owner = "Lena", Balance = 100m };
var b = new Account { Owner = "Omar", Balance = 50m };
// a and b are two independent objects of the same class
This works, but anyone can write a.Balance = -1000000;. Nothing protects the object's rules.
Encapsulation
Encapsulation hides an object's state and exposes only operations that keep it valid. Fields become private; the outside world uses methods and properties.
public class Account
{
private decimal _balance;
public Account(string owner, decimal openingBalance)
{
if (string.IsNullOrWhiteSpace(owner)) throw new ArgumentException("Owner is required.", nameof(owner));
if (openingBalance < 0) throw new ArgumentOutOfRangeException(nameof(openingBalance));
Owner = owner;
_balance = openingBalance;
}
public string Owner { get; } // read-only after construction
public decimal Balance => _balance; // read-only to callers
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
_balance += amount;
}
public virtual void Withdraw(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
if (amount > _balance) throw new InvalidOperationException("Insufficient funds.");
_balance -= amount;
}
protected void Debit(decimal amount) => _balance -= amount; // for derived classes
}
The rules live in one place. A caller can no longer create an account without an owner or with a negative balance, and the balance changes only through Deposit and Withdraw. Access modifiers do the enforcing: private is visible only inside the class, protected also in derived classes, internal within the assembly, public everywhere.
Inheritance
A derived class reuses everything a base class offers and adds or changes behaviour. A savings account is an account with interest:
public class SavingsAccount : Account
{
public SavingsAccount(string owner, decimal openingBalance, decimal annualRate)
: base(owner, openingBalance) // run the base constructor first
{
AnnualRate = annualRate;
}
public decimal AnnualRate { get; }
public void AddMonthlyInterest()
{
Deposit(Math.Round(Balance * AnnualRate / 12, 2));
}
}
: base(...) passes arguments to the base constructor, which keeps its validation. C# supports single inheritance of classes: a class has exactly one base class (object if none is written).
Polymorphism
Polymorphism means a call is resolved according to the object's actual type at run time. The base class marks a method virtual; a derived class replaces it with override:
public class CheckingAccount : Account
{
public CheckingAccount(string owner, decimal openingBalance, decimal overdraftLimit)
: base(owner, openingBalance)
{
OverdraftLimit = overdraftLimit;
}
public decimal OverdraftLimit { get; }
public override void Withdraw(decimal amount)
{
if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
if (amount > Balance + OverdraftLimit) throw new InvalidOperationException("Overdraft limit exceeded.");
Debit(amount);
}
}
var accounts = new List<Account>
{
new SavingsAccount("Lena", 100m, 0.02m),
new CheckingAccount("Omar", 50m, 200m)
};
foreach (Account acc in accounts)
{
try
{
acc.Withdraw(120m); // which Withdraw runs depends on the real type
Console.WriteLine($"{acc.Owner}: {acc.Balance}");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"{acc.Owner}: {ex.Message}");
}
}
// Lena: Insufficient funds.
// Omar: -70
The loop only knows it has Account references, yet Omar's checking account applies its overdraft rule. That is run-time (dynamic) polymorphism. Method overloading, several methods with the same name and different parameters, is sometimes called compile-time polymorphism:
public void Deposit(decimal amount) { /* ... */ }
public void Deposit(decimal amount, string reference) { /* ... */ }
A related keyword causes confusion: new on a member hides the base member instead of overriding it, so the base version still runs when called through a base-typed variable. It is rarely what you want.
Abstraction: abstract classes and interfaces
Abstraction means depending on what something does rather than how. An abstract class cannot be instantiated and can declare members that derived classes must implement:
public abstract class Fee
{
public abstract decimal Calculate(decimal amount);
public override string ToString() => GetType().Name;
}
public class FlatFee : Fee
{
public override decimal Calculate(decimal amount) => 1.50m;
}
public class PercentageFee : Fee
{
private readonly decimal _rate;
public PercentageFee(decimal rate) => _rate = rate;
public override decimal Calculate(decimal amount) => Math.Round(amount * _rate, 2);
}
An interface is a pure contract that any class can sign, whatever its base class, and a class can implement several:
public interface IStatementPrinter
{
string Print(Account account);
}
public class TextStatementPrinter : IStatementPrinter
{
public string Print(Account account) => $"{account.Owner}: {account.Balance:C}";
}
| Abstract class | Interface | |
|---|---|---|
| How many per class | One | Many |
| Instance fields and constructors | Yes | No |
| Implemented members | Yes | Since C# 8, default implementations |
| Typical use | Shared code for a family of related types | A capability unrelated types can offer |
Composition
Not every relationship is "is a". An account has a fee policy and a statement printer; it is not one. Holding objects and delegating to them is composition, and it keeps hierarchies shallow:
public class FeeAccount : Account
{
private readonly Fee _fee;
public FeeAccount(string owner, decimal opening, Fee fee) : base(owner, opening) => _fee = fee;
public override void Withdraw(decimal amount)
{
base.Withdraw(amount + _fee.Calculate(amount)); // reuse the base rules, add the fee
}
}
Changing the fee rule now means passing a different Fee object, not writing a new subclass for every combination.
Mistakes interviewers like to ask about
- Public fields everywhere. They make encapsulation impossible; use properties.
- Inheritance for reuse only. If the derived class cannot be used wherever the base is expected (Liskov substitution), prefer composition.
- Forgetting
virtual. Without it,overridedoes not compile, andnewsilently hides. - Calling virtual methods from constructors. The override runs before the derived constructor body has initialised its fields.
- Sealing too early or too late.
sealedprevents inheritance; use it when a class is not designed to be extended.
More: C vs C++ in object-oriented terms and the 100 interview questions.
Official documentation
- Microsoft Learn: Object-Oriented programming (C#)
- Microsoft Learn: Inheritance, Polymorphism
- Microsoft Learn: abstract, interface, Access modifiers