Object-Oriented C#

Inheritance

Reuse and specialize behavior through a base class.

Introduction

Inheritance models an is-a relationship and should be used when derived objects genuinely satisfy the base contract.

The base constructor initializes shared state. The derived class overrides a virtual method to specialize behavior.

Runnable C# example

C#
Run code →
Program.cs
using System;

class Employee(string name)
{
    public string Name { get; } = name;
    public virtual string Describe() => Name;
}

class Developer(string name, string language) : Employee(name)
{
    public override string Describe() => $"{Name} writes {language}";
}

class Program
{
    static void Main() => Console.WriteLine(new Developer("Ada", "C#").Describe());
}
Result of running the code
Ada writes C#

Practice with the debugger

Set a breakpoint on an important assignment or condition, click Debug, and inspect the local values before stepping to the next line.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges