C# inheritance, interfaces and polymorphism
This is the last page of the C# basics path. The previous page built single classes; this one connects them. Inheritance lets one class reuse and extend another, abstract classes share an algorithm while leaving steps open, interfaces describe what a type can do without saying how, and polymorphism lets one piece of code work with all of them. The samples model OrdersPortal shipments, payment methods, notifications and order events.
What you’ll build
Section titled “What you’ll build”You will finish with an order processor that charges an order through any payment method (card or bank transfer) and tells any number of notifiers (customer message, audit log) about the result. The processor depends only on an abstract class and an interface, so adding a new payment method or notifier needs no change to it. Along the way you will see the difference between overriding and hiding a method, and when to choose an abstract class over an interface.
Prerequisites
Section titled “Prerequisites”- The .NET 10 SDK or later. The samples were compiled and run with .NET SDK 10.0.115 (C# 14). The polymorphism sample uses a collection expression (
[ ... ]), which needs C# 12; everything else works on much older versions. - A console project (
dotnet new console -o OrdersPortal.Basics). ReplaceProgram.cswith each sample and rundotnet run. - Classes, constructors and access modifiers from classes and objects.
Inheritance
Section titled “Inheritance”Inheritance lets a derived class take on the members of a base class and add or change behavior. You write it with a colon: class ExpressShipment : Shipment. An express shipment is a shipment, so it has OrderNumber, WeightKg and Describe without redeclaring them, and it can be used anywhere a Shipment is expected.
Four keywords control how this works:
: base(...)after a derived constructor calls the base constructor first, so the base part of the object is initialized before the derived part.virtualon a base member allows derived classes to replace it. Members are not virtual by default in C#.overridein the derived class replaces avirtual(orabstract) member. Inside it,base.Cost()calls the base version, so you can extend rather than rewrite.sealedon a class stops further derivation; on anoverrideit stops further overriding.
A class has exactly one base class. If you write none, it derives from object, which is where ToString, Equals and GetType come from.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var standard = new Shipment("ORD-1001", 2m);var express = new ExpressShipment("ORD-1002", 2m, "before 10:00");
Console.WriteLine(standard.Describe());Console.WriteLine(express.Describe());Console.WriteLine($"Express cost: {express.Cost()}");
Shipment asBase = express; // a derived object can be used where the base is expectedConsole.WriteLine(asBase.Cost()); // still runs ExpressShipment.Cost (override)Console.WriteLine(asBase is ExpressShipment);
// Hiding versus overridingShipment hidden = new LegacyShipment("ORD-1003", 1m);Console.WriteLine(hidden.Label()); // base Label: hiding does not overrideConsole.WriteLine(((LegacyShipment)hidden).Label()); // the hiding method needs the derived type
public class Shipment{ public Shipment(string orderNumber, decimal weightKg) { OrderNumber = orderNumber; WeightKg = weightKg; }
public string OrderNumber { get; } public decimal WeightKg { get; }
public virtual decimal Cost() => 4.95m + WeightKg * 1.20m; // virtual: derived classes may override
public string Describe() => $"{GetType().Name} {OrderNumber}: {WeightKg} kg, {Cost()}";
public string Label() => $"STANDARD {OrderNumber}";}
public class ExpressShipment : Shipment // ": Shipment" means "derives from Shipment"{ public ExpressShipment(string orderNumber, decimal weightKg, string deliveryWindow) : base(orderNumber, weightKg) // run the base constructor first { DeliveryWindow = deliveryWindow; }
public string DeliveryWindow { get; } // new member, only on ExpressShipment
public override decimal Cost() => base.Cost() * 2 + 5m; // reuse the base logic, then extend it}
public sealed class LegacyShipment : Shipment // sealed: no class can derive from this one{ public LegacyShipment(string orderNumber, decimal weightKg) : base(orderNumber, weightKg) { }
public new string Label() => $"LEGACY {OrderNumber}"; // new: hides Shipment.Label, does not override}Output:
Shipment ORD-1001: 2 kg, 7.35ExpressShipment ORD-1002: 2 kg, 19.70Express cost: 19.7019.70TrueSTANDARD ORD-1003LEGACY ORD-1003The last two lines show a trap. LegacyShipment.Label is declared with new, which hides the base method instead of overriding it. With hiding, the compiler picks the method from the variable’s declared type, so a Shipment variable calls Shipment.Label even though the object is a LegacyShipment. With override, the object’s actual type always wins, as asBase.Cost() shows. If you redeclare a method without either keyword, the compiler warns with CS0108 and hides. Hiding is rarely what you want; if a base method should vary, make it virtual.
Use inheritance only for a genuine “is a” relationship where the derived class can stand in for the base everywhere. When you only want to reuse some code, giving one class a field of another type (composition) is usually simpler and less fragile.
Abstract classes
Section titled “Abstract classes”An abstract class is a base class that cannot be instantiated on its own; it exists to be derived from. It can mix finished members that every derived class shares with abstract members, which have no body and must be overridden by every non-abstract derived class. Abstract members are implicitly virtual.
This suits a fixed algorithm with variable steps. Every payment validates the amount, adds a fee and authorizes the total; only the fee and the authorization differ. The abstract PaymentMethod owns the algorithm in Pay, declares Name and Authorize as abstract, and gives Fee a virtual default of zero that card payments override.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
PaymentMethod card = new CardPayment("4242");PaymentMethod transfer = new BankTransfer("PT50-0000-0000");
Console.WriteLine(card.Pay(120.00m));Console.WriteLine(transfer.Pay(120.00m));Console.WriteLine(card.Pay(-5m));// var p = new PaymentMethod(); // CS0144: cannot create an instance of the abstract type
public abstract class PaymentMethod{ // Shared, finished logic that every payment method gets public string Pay(decimal amount) { if (amount <= 0) { return $"{Name}: rejected, amount must be positive"; } decimal fee = Fee(amount); return $"{Name}: charged {amount + fee} (fee {fee}) via {Authorize(amount + fee)}"; }
public abstract string Name { get; } // abstract: no body, derived classes must supply it protected abstract string Authorize(decimal total); protected virtual decimal Fee(decimal amount) => 0.00m; // virtual: a default derived classes may replace}
public class CardPayment : PaymentMethod{ private readonly string _lastFour;
public CardPayment(string lastFour) => _lastFour = lastFour;
public override string Name => "Card"; protected override string Authorize(decimal total) => $"card ending {_lastFour}"; protected override decimal Fee(decimal amount) => Math.Round(amount * 0.015m, 2);}
public class BankTransfer : PaymentMethod{ private readonly string _iban;
public BankTransfer(string iban) => _iban = iban;
public override string Name => "Bank transfer"; protected override string Authorize(decimal total) => $"transfer to {_iban}";}Output:
Card: charged 121.80 (fee 1.80) via card ending 4242Bank transfer: charged 120.00 (fee 0.00) via transfer to PT50-0000-0000Card: rejected, amount must be positiveThe callers hold PaymentMethod variables and call Pay; they never need to know which class they have. Because the validation lives in the base class, no derived class can forget it. Note that Authorize and Fee are protected: derived classes implement them, but outside code can only call the public Pay. If a derived class omits an abstract member, the compiler reports CS0534; if it writes the method without override, it also warns with CS0114 that the method hides the abstract one.
Interfaces
Section titled “Interfaces”An interface is a contract: a named set of members that an implementing class or struct promises to provide. It says what a type can do, not how, and usually holds no state. A class can derive from only one base class but can implement any number of interfaces, which makes interfaces the main tool for connecting unrelated types. By convention their names start with I.
A class implements an interface member with a public member of the same signature. Alternatively it can use an explicit implementation, written decimal ICostTracked.TotalCost, which is only reachable through the interface type. That keeps rarely used or conflicting members off the class’s own public surface.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
INotifier[] notifiers = { new EmailNotifier("ana@example.test"), new SmsNotifier("+1-555-0100") };foreach (INotifier notifier in notifiers){ notifier.Send("Your order ORD-1001 has shipped");}
var sms = new SmsNotifier("+1-555-0101");sms.Send("Code 1234");Console.WriteLine($"SMS cost so far: {((ICostTracked)sms).TotalCost}"); // explicit implementation: reach it through the interface
IDiscountRule[] rules = { new BulkDiscount(), new MemberDiscount() };decimal subtotal = 250m;decimal best = 0m;foreach (IDiscountRule rule in rules){ best = Math.Max(best, rule.DiscountFor(subtotal, isMember: true));}Console.WriteLine($"Best discount on {subtotal}: {best}");
// An interface is a contract: members with no state that implementers must providepublic interface INotifier{ void Send(string message);}
public interface ICostTracked{ decimal TotalCost { get; }}
public interface IDiscountRule{ decimal DiscountFor(decimal subtotal, bool isMember);}
public class EmailNotifier : INotifier{ private readonly string _address;
public EmailNotifier(string address) => _address = address;
public void Send(string message) => Console.WriteLine($"Email to {_address}: {message}");}
// A class can implement several interfaces (but derive from only one class)public class SmsNotifier : INotifier, ICostTracked{ private readonly string _phone; private decimal _cost;
public SmsNotifier(string phone) => _phone = phone;
public void Send(string message) { _cost += 0.05m; Console.WriteLine($"SMS to {_phone}: {message}"); }
decimal ICostTracked.TotalCost => _cost; // explicit interface implementation}
public class BulkDiscount : IDiscountRule{ public decimal DiscountFor(decimal subtotal, bool isMember) => subtotal >= 200m ? 20m : 0m;}
public class MemberDiscount : IDiscountRule{ public decimal DiscountFor(decimal subtotal, bool isMember) => isMember ? subtotal * 0.10m : 0m;}Output:
Email to ana@example.test: Your order ORD-1001 has shippedSMS to +1-555-0100: Your order ORD-1001 has shippedSMS to +1-555-0101: Code 1234SMS cost so far: 0.05Best discount on 250: 25.00The loops are written against INotifier and IDiscountRule, so they work with any implementation, including ones written later or fakes in unit tests. This is why dependency injection in ASP.NET Core is built around interfaces.
Interfaces have grown since C# 1.0. C# 8 added default interface methods, which give a member a body so an interface can gain members without breaking existing implementers; the methods and lambdas hub covers them. C# 11 added static abstract members, which power generic math, covered in the memory and performance hub.
Abstract class or interface
Section titled “Abstract class or interface”| Choose | When |
|---|---|
| Abstract class | Related types share real implementation or state, and you want to enforce a common algorithm, as PaymentMethod.Pay does. |
| Interface | Unrelated types need a common capability, a type needs several capabilities, or you want to swap implementations in tests. |
| Both | An interface for callers, plus an optional abstract base class that implementers can derive from to save work. |
Polymorphism
Section titled “Polymorphism”Polymorphism (“many forms”) means one piece of code works with objects of different types and each object runs its own version of a method. In C# it comes from virtual and override (or interface implementations): the call e.Describe() is resolved at run time from the object’s actual type, not from the variable’s declared type. This is called dynamic dispatch.
The list below is typed as List<OrderEvent> but holds four different event classes. One loop prints all of them, and each prints its own description. Adding a new event type needs no change to the loop.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
// One list typed by the base class, holding several derived typesList<OrderEvent> timeline =[ new OrderPlaced("ORD-1001", 3), new PaymentCaptured("ORD-1001", 129.12m), new OrderShipped("ORD-1001", "TRK-55"), new OrderEvent("ORD-1001"),];
foreach (OrderEvent e in timeline){ Console.WriteLine(e.Describe()); // the runtime type decides which override runs}
// Type checks when you need something only one derived type hasforeach (OrderEvent e in timeline){ if (e is OrderShipped shipped) // type pattern: test and cast in one step { Console.WriteLine($"Tracking number: {shipped.TrackingNumber}"); }}
public class OrderEvent{ public OrderEvent(string orderNumber) => OrderNumber = orderNumber;
public string OrderNumber { get; }
public virtual string Describe() => $"{OrderNumber}: {GetType().Name}";}
public class OrderPlaced : OrderEvent{ private readonly int _items; public OrderPlaced(string orderNumber, int items) : base(orderNumber) => _items = items; public override string Describe() => $"{OrderNumber}: placed with {_items} items";}
public class PaymentCaptured : OrderEvent{ private readonly decimal _amount; public PaymentCaptured(string orderNumber, decimal amount) : base(orderNumber) => _amount = amount; public override string Describe() => $"{OrderNumber}: payment of {_amount} captured";}
public class OrderShipped : OrderEvent{ public OrderShipped(string orderNumber, string trackingNumber) : base(orderNumber) => TrackingNumber = trackingNumber; public string TrackingNumber { get; } public override string Describe() => $"{base.Describe()}, tracking {TrackingNumber}";}Output:
ORD-1001: placed with 3 itemsORD-1001: payment of 129.12 capturedORD-1001: OrderShipped, tracking TRK-55ORD-1001: OrderEventTracking number: TRK-55Sometimes you need a member that only one derived type has, such as the tracking number. The type pattern e is OrderShipped shipped tests the type and gives you a typed variable in one step, without a cast that could throw InvalidCastException. Use it sparingly: if a loop checks for many concrete types, the behavior probably belongs in a virtual method instead. The pattern matching hub shows the full range of patterns.
Complete working result
Section titled “Complete working result”The order processor depends only on PaymentMethod (an abstract class with a shared TryCharge algorithm) and INotifier (an interface with two unrelated implementations). Polymorphism does the rest: payment.TryCharge runs the right fee and description for each payment method, and the foreach reaches every notifier through the interface.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var processor = new OrderProcessor(new INotifier[] { new ConsoleNotifier(), new AuditLog() });
processor.Checkout("ORD-2001", 80.00m, new CardPayment("4242"));processor.Checkout("ORD-2002", 250.00m, new BankTransfer());processor.Checkout("ORD-2003", 0m, new CardPayment("1881"));
// Contract: anything that can be told about an orderpublic interface INotifier{ void Notify(string orderNumber, string message);}
public class ConsoleNotifier : INotifier{ public void Notify(string orderNumber, string message) => Console.WriteLine($" [customer] {orderNumber}: {message}");}
public class AuditLog : INotifier{ private int _entries; public void Notify(string orderNumber, string message) => Console.WriteLine($" [audit #{++_entries}] {orderNumber}");}
// Shared algorithm with steps that derived classes fill inpublic abstract class PaymentMethod{ public bool TryCharge(decimal amount, out string receipt) { if (amount <= 0) { receipt = "amount must be positive"; return false; } decimal total = amount + Fee(amount); receipt = $"{total} by {Describe()}"; return true; }
protected abstract string Describe(); protected virtual decimal Fee(decimal amount) => 0.00m;}
public class CardPayment : PaymentMethod{ private readonly string _lastFour; public CardPayment(string lastFour) => _lastFour = lastFour; protected override string Describe() => $"card ending {_lastFour}"; protected override decimal Fee(decimal amount) => Math.Round(amount * 0.015m, 2);}
public class BankTransfer : PaymentMethod{ protected override string Describe() => "bank transfer";}
// Depends only on the abstractions, so new payment methods or notifiers need no changes herepublic class OrderProcessor{ private readonly IReadOnlyList<INotifier> _notifiers;
public OrderProcessor(IReadOnlyList<INotifier> notifiers) => _notifiers = notifiers;
public void Checkout(string orderNumber, decimal amount, PaymentMethod payment) { Console.WriteLine($"{orderNumber} ({payment.GetType().Name})"); string message = payment.TryCharge(amount, out string receipt) ? $"paid {receipt}" : $"payment failed: {receipt}"; foreach (INotifier notifier in _notifiers) { notifier.Notify(orderNumber, message); } }}Output:
ORD-2001 (CardPayment) [customer] ORD-2001: paid 81.20 by card ending 4242 [audit #1] ORD-2001ORD-2002 (BankTransfer) [customer] ORD-2002: paid 250.00 by bank transfer [audit #2] ORD-2002ORD-2003 (CardPayment) [customer] ORD-2003: payment failed: amount must be positive [audit #3] ORD-2003As an exercise, add a GiftCardPayment that rejects amounts over a balance, and an SmsNotifier. OrderProcessor should not need a single change.
Troubleshooting
Section titled “Troubleshooting”Exact messages from the .NET 10 SDK compiler:
| Error | Cause | Fix |
|---|---|---|
CS0506: 'Sq.Name()': cannot override inherited member 'Shape.Name()' because it is not marked virtual, abstract, or override |
Overriding a non-virtual method. | Mark the base member virtual if it is meant to vary. |
warning CS0108: 'D.Hi()' hides inherited member 'Base.Hi()'. Use the new keyword if hiding was intended. |
A derived method has the same signature as a non-virtual base method. | Make the base virtual and use override, or rename the method. |
CS0534: 'Circle' does not implement inherited abstract member 'Shape.Area()' |
A concrete class misses an abstract member, or implements it without override. |
Add the member with override. |
CS0144: Cannot create an instance of the abstract type or interface 'Shape' |
new on an abstract class or interface. |
Create a concrete derived class instead. |
CS0535: 'C3' does not implement interface member 'IShape.GetArea()' |
An interface member is missing. | Implement every member of the interface. |
CS0737: 'C2' does not implement interface member 'IShape.GetArea()'. 'C2.GetArea()' cannot implement an interface member because it is not public. |
The implementing method is private. |
Make it public, or use an explicit implementation (double IShape.GetArea()). |
CS1721: Class 'AB' cannot have multiple base classes: 'A' and 'B' |
Two base classes in the list. | Derive from one class and turn the other into an interface. |
CS0509: 'Z2': cannot derive from sealed type 'Z' |
Deriving from a sealed class. |
Use composition: hold an instance of the sealed class in a field. |
Check your understanding
Section titled “Check your understanding”- What is the difference between overriding with
overrideand hiding withnew? An override is chosen from the object’s runtime type, so a base-typed variable still runs the derived version. A hidden method is chosen from the variable’s compile-time type, so a base-typed variable runs the base version. - Can a class inherit from two classes? From two interfaces? One class only, but any number of interfaces.
- When would you choose an abstract class over an interface? When related types share implementation or state, or you want to enforce one algorithm with variable steps. Choose an interface for a capability that unrelated types share or that tests need to replace.
- What must a non-abstract class do when it derives from an abstract class? Override every abstract member, or be declared abstract itself.
- A loop over
List<Shape>callsshape.Area(). Which implementation runs for aCircleelement?Circle’s override, as long asAreaisvirtualorabstractinShape. The declared type of the list does not matter.
Next steps
Section titled “Next steps”You have finished the basics path. Good next stops are the types and records hub for records, tuples and union types, and the object construction and initialization hub for modern ways to build objects. The topic hubs index lists every hub in a suggested order.
Related pages
Section titled “Related pages”- C# basics overview: the full reading path.
- Types and records hub: records, closed hierarchies and union types, which build on the class hierarchies on this page.
- Pattern matching hub: type patterns and
switchover class hierarchies. - Methods and lambdas hub: default interface methods, and extension methods, which add members to a type without inheritance.