bhylu.com

Advertisements

C# Inheritance

Use an abstract base for shared behaviour and override a method through the base contract.

How it works

An abstract class can supply common implementation while requiring derived behaviour. A virtual method allows an override; override asks the compiler to verify the relationship. Use public inheritance when a derived object can honour the base contract wherever that base is expected. C# classes inherit one direct base class, while interfaces supply multiple capabilities. Keep shared state private unless a carefully designed extension contract genuinely needs protected access.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;

internal static class Program
{
    private static void Main(string[] args)
    {
        SessionFormat[] formats = { new InPerson(), new Remote() };
        foreach (SessionFormat format in formats) Console.WriteLine(format.Description());
    }
}

internal abstract class SessionFormat
{
    protected abstract string Location { get; }
    public string Description() => "Workshop: " + Location;
}
internal sealed class InPerson : SessionFormat { protected override string Location => "Studio"; }
internal sealed class Remote : SessionFormat { protected override string Location => "Online"; }

Expected result

Workshop: Studio
Workshop: Online

The base method formats the description while each derived class supplies its location. Calling through the base reference still reaches the appropriate overridden property. sealed prevents further subclassing where the extension contract is intentionally closed. Method hiding with new is different from overriding and should not be used accidentally to simulate polymorphism.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.