OSC#.008: C# Inheritance — Base Classes, Virtual Methods and Runtime Polymorphism

Cinematic anime illustration of a software engineer studying a layered network equipment inventory application.

Open-Source C# Programming • Intermediate • Estimated study time: 35 minutes

An equipment inventory may contain switches, routers and generic devices. Each has an identifier, but each may describe its function differently. Inheritance models a shared contract while allowing specialized behavior. The preceding classes and objects lesson introduced constructors, properties and encapsulation. The next step is to reuse those structures without duplicating their behavior.

Prerequisites and learning objectives

Install a supported .NET SDK using the C# toolchain lesson. Use a terminal and text editor in a disposable project directory. Learners will declare a derived class, initialize a base constructor, override a virtual method, predict dispatch through base references and distinguish overriding from hiding.

Inheritance and virtual dispatch

The colon following a class name identifies its base class. C# permits a class to inherit directly from one class, although it may implement multiple interfaces. Constructors are not inherited. A derived constructor can invoke a base constructor with base(arguments). The base type exposes a contract that derived objects must respect. Microsoft’s inheritance reference distinguishes accessible inherited members from constructors and other implementation details.

Teddy Smith demonstrates inheritance and the virtual and override modifiers in the following original YouTube tutorial:

Teddy Smith explains how a derived C# class can specialize inherited behavior. Watch at source.

A virtual method permits specialization. An override replaces the inherited virtual implementation for runtime dispatch. By contrast, a nonvirtual method cannot be overridden. A method declared with new hides an inherited member, so ordinary calls can select different methods depending on the compile-time reference type. Revisit method overloading for the separate concept of choosing among signatures.

Laboratory: polymorphic device inventory

Create a console application in an empty local directory using the following commands:

dotnet new console -n InventoryLab
cd InventoryLab

Replace Program.cs with the following complete source:

using System;

class Device
{
    public string Name { get; }
    public Device(string name) => Name = name;
    public virtual string Describe() => Name + “: device”;
}

class Switch : Device
{
    public Switch(string name) : base(name) { }
    public override string Describe() => Name + “: switch”;
}

class Router : Device
{
    public Router(string name) : base(name) { }
    public override string Describe() => Name + “: router”;
}

class Program
{
    static void Main()
    {
        Device[] inventory = {
            new Device(“A”),
            new Switch(“B”),
            new Router(“C”)
        };
        foreach (Device item in inventory)
            Console.WriteLine(item.Describe());
    }
}

Compile and execute the program using the following commands:

dotnet build
dotnet run –no-build

The expected output is:

A: device
B: switch
C: router

Although every array element is referenced as Device, the runtime object determines which virtual implementation runs. The constructor for Switch passes its identifier to Device, which initializes the read-only Name property. The foreach loop does not need a separate conditional branch for each subtype. The expected output follows from language semantics; it has not been executed in the editorial environment.

Overriding versus hiding

Replace the Switch override declaration with public new string Describe() while leaving the other code unchanged. The call through Device now uses Device.Describe for the switch element, yielding B: device. A direct call through a Switch variable instead selects the hidden member. Consult Microsoft’s override and new reference for the distinction.

The instructor demonstrates inheritance and polymorphism as related object-oriented programming techniques. Watch at source.

Verification and troubleshooting

If the compiler rejects override, verify the inherited method is virtual and that the signature matches. If a constructor requires an argument, supply it using base. Use the debugger to inspect the runtime type of each object. Compare the output against the expected sequence rather than relying on compilation alone. The control flow lesson explains the foreach loop used to traverse the inventory.

Exercises and answer key

1. Add a Firewall subclass with an overridden description. 2. Explain why all subclasses fit in Device[]. 3. Predict the output when the Router override is removed. 4. Explain why removing virtual prevents the existing overrides. 5. Describe when composition may be preferable to inheritance.

Answers: 1. Inherit from Device, call base(name) and return Name + “: firewall” from an override. 2. Each object is assignable to its base type. 3. C: device. 4. The base member no longer supports virtual dispatch. 5. Prefer composition when an object merely uses another service rather than representing a genuine specialization.

Elementary conclusion

Inheritance shares a common type and behavior; polymorphism allows specialized objects to respond differently through that shared type. Use encapsulation to preserve the base contract and verify both the general and specialized behaviors before deploying a class hierarchy.

We volunteer daily to ensure the credibility of the information on the platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiative, please scan the QR code below.

Optional 5,000-satoshi contribution QR
Optional 5,000-satoshi contribution. Independently confirm the wallet address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb and payment amount before sending.

BitcoinVersus.tech is not a financial advisor. The media platform reports on financial subjects purely for informational purposes.

Leave a Reply