10. Inheritance, Polymorphism and Interfaces
Inheritance lets a class reuse another class: class Dog : Animal makes Dog a derived (child) class that gets the public and protected members of its base (parent) class. It models an 'is-a' relationship (a Dog is an Animal). A derived constructor passes data to the base constructor with : base(...), and base.Method() calls the parent's version. C# allows one base class but many interfaces. Every class ultimately inherits from System.Object, which supplies ToString, Equals and GetHashCode.
Polymorphism means one call, many behaviours. Mark a base method virtual and override it in a derived class, so the version that runs depends on the real type of the object at run time, even when it is stored in a base-type variable. An abstract class cannot be instantiated and may contain abstract members that every derived class must implement. sealed stops further inheritance or overriding. Using new on a member hides the base member instead of overriding it (usually a mistake).
An interface defines a contract of members (methods, properties, events) with no data; any class that implements it must provide them. A class can implement many interfaces, and code can depend on the interface instead of a concrete class, which makes programs flexible and testable. Use the is and as operators and pattern matching to check an object's real type, and implement built-in interfaces such as IComparable<T>, IEnumerable<T> and IDisposable to make your types work with the rest of .NET.
- Virtual and override
- Base constructors, protected members and base calls
- Abstract classes
- Interface
- One interface, many classes
- Implementing several interfaces
- Casting and type checks (is, as)
- override vs new (hiding) and sealed
- Built-in interfaces: IComparable and IDisposable
- Default interface members and composition
Key points to remember
- Use inheritance for a real 'is-a' relationship. For 'has-a' use composition (a Car has an Engine field) instead; it is more flexible.
- Base class members that derived classes need should be protected; everything else private.
- Upcasting (Dog to Animal) is implicit and always safe. Downcasting needs a cast or pattern match and can fail, so prefer is / as.
- Abstract class: shared code and state, single inheritance, can have constructors. Interface: only a contract, many can be implemented, no instance fields.
- Interface names start with I (IPayable). Prefer small, focused interfaces (ISP in SOLID).
- A derived class should be usable anywhere its base class is (Liskov substitution). If an override throws NotImplementedException, the hierarchy is probably wrong.
- Override must match the base signature; a method not marked virtual, abstract or override cannot be overridden.
- Interfaces can have default method bodies (C# 8), static members, and can be implemented explicitly (void IFlyer.Fly()) to avoid name clashes.
- Constructors run base first, then derived. Constructors are not inherited, so each derived class defines its own.
Example 1: Virtual and override
Animal[] pets = { new Dog(), new Cat(), new Animal() };
foreach (var pet in pets)
Console.WriteLine(pet.Speak());
class Animal
{
public virtual string Speak() => "...";
}
class Dog : Animal
{
public override string Speak() => "Woof";
}
class Cat : Animal
{
public override string Speak() => "Meow";
}
Show output
OutputWoof Meow ...
Example 2: Base constructors, protected members and base calls
var e = new Employee("Ann", 5000m);
Console.WriteLine(e.Describe());
class Person
{
public string Name { get; }
protected int Id { get; }
public Person(string name) { Name = name; Id = 1; }
public virtual string Describe() => $"Person: {Name}";
}
class Employee : Person
{
public decimal Salary { get; }
public Employee(string name, decimal salary) : base(name) // calls Person(name)
{
Salary = salary;
}
public override string Describe() => base.Describe() + $", earns {Salary}";
}
Show output
OutputPerson: Ann, earns 5000
Example 3: Abstract classes
Shape[] shapes = { new Circle(1), new Square(2) };
foreach (var s in shapes)
Console.WriteLine($"{s.Name}: {s.Area():F2}");
abstract class Shape
{
public abstract double Area(); // no body: must be overridden
public string Name => GetType().Name; // shared code
}
class Circle : Shape
{
private readonly double _r;
public Circle(double r) { _r = r; }
public override double Area() => Math.PI * _r * _r;
}
class Square : Shape
{
private readonly double _side;
public Square(double side) { _side = side; }
public override double Area() => _side * _side;
}
Show output
OutputCircle: 3.14 Square: 4.00
Example 4: Interface
IPayable p = new Employee();
Console.WriteLine(p.Pay());
interface IPayable
{
decimal Pay();
}
class Employee : IPayable
{
public decimal Pay() => 5000m;
}
Show output
Output5000
Example 5: One interface, many classes
var staff = new List<IPayable> { new Salaried(5000m), new Hourly(150m, 20) };
decimal total = 0;
foreach (IPayable p in staff)
{
Console.WriteLine($"{p.GetType().Name}: {p.Pay()}");
total += p.Pay();
}
Console.WriteLine("Total: " + total);
interface IPayable { decimal Pay(); }
class Salaried : IPayable
{
private readonly decimal _monthly;
public Salaried(decimal monthly) { _monthly = monthly; }
public decimal Pay() => _monthly;
}
class Hourly : IPayable
{
private readonly decimal _rate; private readonly int _hours;
public Hourly(decimal rate, int hours) { _rate = rate; _hours = hours; }
public decimal Pay() => _rate * _hours;
}
Show output
OutputSalaried: 5000 Hourly: 3000 Total: 8000
Example 6: Implementing several interfaces
var duck = new Duck();
IFlyer f = duck;
f.Fly();
if (f is ISwimmer s) s.Swim(); // test and use another interface
((ISwimmer)duck).Swim();
interface IFlyer { void Fly(); }
interface ISwimmer { void Swim(); }
class Duck : IFlyer, ISwimmer
{
public void Fly() => Console.WriteLine("Duck flies");
public void Swim() => Console.WriteLine("Duck swims");
}
Show output
OutputDuck flies Duck swims Duck swims
Example 7: Casting and type checks (is, as)
Animal a = new Dog(); // upcast, implicit
Console.WriteLine(a is Dog);
Dog? d = a as Dog; // null if not a Dog
Console.WriteLine(d != null);
Cat? c = a as Cat;
Console.WriteLine(c == null);
if (a is Dog dog) Console.WriteLine(dog.Fetch());
try { Cat bad = (Cat)a; }
catch (InvalidCastException) { Console.WriteLine("Invalid cast"); }
class Animal { }
class Dog : Animal { public string Fetch() => "Fetching"; }
class Cat : Animal { }
Show output
OutputTrue True True Fetching Invalid cast
Example 8: override vs new (hiding) and sealed
A x = new B();
Console.WriteLine(x.Who()); // override: B's version runs
Console.WriteLine(x.Name()); // hidden: type of variable decides (A)
Console.WriteLine(((B)x).Name()); // B's hiding member
class A
{
public virtual string Who() => "A";
public string Name() => "A-name";
}
class B : A
{
public sealed override string Who() => "B"; // no class can override it again
public new string Name() => "B-name"; // hides, does not override
}
Show output
OutputB A-name B-name
Example 9: Built-in interfaces: IComparable and IDisposable
var list = new List<Student> { new("Ann", 80), new("Ben", 65), new("Cy", 90) };
list.Sort(); // uses CompareTo
foreach (var s in list)
Console.WriteLine($"{s.Name} {s.Mark}");
using (var res = new Resource())
Console.WriteLine("Using resource");
record Student(string Name, int Mark) : IComparable<Student>
{
public int CompareTo(Student? other)
{
if (other is null) return 1;
return Mark.CompareTo(other.Mark);
}
}
class Resource : IDisposable
{
public void Dispose() => Console.WriteLine("Disposed");
}
Show output
OutputBen 65 Ann 80 Cy 90 Using resource Disposed
Example 10: Default interface members and composition
ILogger logger = new ConsoleLogger();
logger.Log("hello");
logger.Warn("careful");
var car = new Car(new Engine()); // composition: a Car HAS an Engine
Console.WriteLine(car.Start());
interface ILogger
{
void Log(string message);
void Warn(string message) => Log("WARNING: " + message); // default body
}
class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine(message);
}
class Engine { public string Run() => "Engine running"; }
class Car
{
private readonly Engine _engine;
public Car(Engine engine) { _engine = engine; }
public string Start() => _engine.Run();
}
Show output
Outputhello WARNING: careful Engine running