C# Tutorial · Object-Oriented C# · Lesson 13 of 22

C# Inheritance and Interfaces

Base classes, virtual/override, abstract classes and interfaces.

Inheritance

A class can inherit from one base class. Mark methods virtual to allow overriding, and override them in the derived class. base calls the parent:

Example 1
var shapes = new Shape[] { new Circle(1), new Rect(2, 3) };
foreach (var s in shapes)
    Console.WriteLine(s.Describe());

abstract class Shape
{
    public abstract double Area();
    public virtual string Describe() => $"{GetType().Name} with area {Area():F2}";
}

class Circle(double r) : Shape
{
    public override double Area() => Math.PI * r * r;
}

class Rect(double w, double h) : Shape
{
    public override double Area() => w * h;
    public override string Describe() => base.Describe() + $" ({w}x{h})";
}

Output

Circle with area 3.14
Rect with area 6.00 (2x3)

Run this on your computer — see “Get Started” for setup.

Interfaces

An interface is a contract; a class can implement many. Program to interfaces to keep code testable — this is how dependency injection works in ASP.NET Core:

Example 2
INotifier[] channels = { new EmailNotifier(), new SmsNotifier() };
foreach (var n in channels)
    Console.WriteLine(n.Send("Your order shipped"));

interface INotifier
{
    string Send(string message);
}

class EmailNotifier : INotifier
{
    public string Send(string message) => $"Email: {message}";
}

class SmsNotifier : INotifier
{
    public string Send(string message) => $"SMS: {message}";
}

Output

Email: Your order shipped
SMS: Your order shipped

Run this on your computer — see “Get Started” for setup.

Test yourself

Which keyword allows a method to be overridden in a derived class?

  1. override
  2. virtual
  3. sealed
  4. static
Show answer

Answer: virtual