Home C# / .NET Polymorphism in C# Explained — Types, Patterns and Real-World Use

Polymorphism in C# Explained — Types, Patterns and Real-World Use

In Plain English 🔥
Imagine a TV remote. You press the power button and it works whether you're pointing it at a Samsung, a Sony, or an LG. You don't need a different remote for each brand — the same button does the right thing for whichever TV is in front of it. Polymorphism in C# is exactly that: one interface, one method call, but the right behaviour kicks in automatically depending on the actual object you're dealing with. That's the whole game.
⚡ Quick Answer
Imagine a TV remote. You press the power button and it works whether you're pointing it at a Samsung, a Sony, or an LG. You don't need a different remote for each brand — the same button does the right thing for whichever TV is in front of it. Polymorphism in C# is exactly that: one interface, one method call, but the right behaviour kicks in automatically depending on the actual object you're dealing with. That's the whole game.

Most C# developers can tell you what polymorphism is. Far fewer can tell you why it exists or when it actually saves you from a mess. That gap — knowing the word but not feeling it — is what turns junior code into a tangle of if/else chains and switch statements that grow without mercy every time a new requirement lands. Polymorphism is what keeps that from happening.

Compile-Time Polymorphism: Method Overloading and Why It's the Simpler Half

Compile-time polymorphism — also called static polymorphism — is resolved by the compiler before your program even runs. In C#, you get this through method overloading: multiple methods sharing the same name but with different parameter signatures. The compiler looks at the arguments you pass and picks the right version. No guessing at runtime.

This is useful when you want one logical operation to handle different input types or different numbers of arguments without forcing the caller to remember six different method names. Think of a logging utility that can accept a plain string, a formatted message with arguments, or an exception object — same concept, different inputs.

The key rule: the methods must differ in the number or type of parameters. Return type alone is not enough — the compiler won't be able to distinguish them at the call site and you'll get a compile error.

OverloadedLogger.cs · CSHARP
123456789101112131415161718192021222324252627282930313233343536373839
using System;

public class AuditLogger
{
    // Overload 1: Simple message log
    public void Log(string message)
    {
        Console.WriteLine($"[INFO] {DateTime.Now:HH:mm:ss} — {message}");
    }

    // Overload 2: Message with a severity level — same name, different signature
    public void Log(string message, string severity)
    {
        Console.WriteLine($"[{severity.ToUpper()}] {DateTime.Now:HH:mm:ss} — {message}");
    }

    // Overload 3: Log an exception directly — compiler picks this when an Exception is passed
    public void Log(Exception exception)
    {
        Console.WriteLine($"[ERROR] {DateTime.Now:HH:mm:ss} — {exception.GetType().Name}: {exception.Message}");
    }
}

class Program
{
    static void Main()
    {
        var logger = new AuditLogger();

        // Compiler resolves this to Overload 1
        logger.Log("User login successful");

        // Compiler resolves this to Overload 2
        logger.Log("Disk space below 10%", "warning");

        // Compiler resolves this to Overload 3
        logger.Log(new InvalidOperationException("Payment gateway timed out"));
    }
}
▶ Output
[INFO] 14:22:05 — User login successful
[WARNING] 14:22:05 — Disk space below 10%
[ERROR] 14:22:05 — InvalidOperationException: Payment gateway timed out
⚠️
Pro Tip:Don't overload just to avoid writing descriptive method names. If the concepts are genuinely different, separate names are cleaner. Overloading shines when it's the *same operation* applied to *different input shapes* — like Log() above, not CreateUser() vs CreateAdmin().

Runtime Polymorphism: Where the Real Magic Happens with Virtual and Override

Runtime polymorphism is resolved while the program is running, not at compile time. This is where C#'s virtual, override, and abstract keywords come in, and it's the type of polymorphism that genuinely changes how you architect software.

Here's the core idea: you write code against a base type, but at runtime the actual derived type's method runs. The base type acts like a contract; every derived class can fulfil that contract in its own way.

The classic mistake beginners make is thinking they need to know which derived type they're working with. You don't — and that's the entire point. When you add a new payment method, a new report format, or a new notification channel, you write one new class and slot it in. Nothing else changes.

Use virtual on the base class method to say 'this can be replaced'. Use override in the derived class to actually replace it. Mark a class abstract when the base version makes no sense on its own and every subclass must provide its own implementation.

PaymentProcessor.cs · CSHARP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
using System;
using System.Collections.Generic;

// Abstract base — there's no such thing as a generic 'payment', so we make it abstract
public abstract class PaymentMethod
{
    public string AccountReference { get; }

    protected PaymentMethod(string accountReference)
    {
        AccountReference = accountReference;
    }

    // Abstract method — every payment type MUST implement this
    public abstract decimal CalculateProcessingFee(decimal orderTotal);

    // Virtual method — has a sensible default, but subclasses CAN override it
    public virtual string GetReceiptLabel()
    {
        return $"Payment via {GetType().Name} (ref: {AccountReference})";
    }

    // Non-virtual — this behaviour never changes regardless of payment type
    public void PrintReceipt(decimal orderTotal)
    {
        decimal fee = CalculateProcessingFee(orderTotal);  // polymorphic call
        Console.WriteLine(GetReceiptLabel());               // polymorphic call
        Console.WriteLine($"  Order total : £{orderTotal:F2}");
        Console.WriteLine($"  Processing  : £{fee:F2}");
        Console.WriteLine($"  Grand total : £{orderTotal + fee:F2}");
        Console.WriteLine();
    }
}

public class CreditCardPayment : PaymentMethod
{
    private readonly bool _isPremiumCard;

    public CreditCardPayment(string cardReference, bool isPremiumCard)
        : base(cardReference)
    {
        _isPremiumCard = isPremiumCard;
    }

    // Credit cards charge 1.5% — 0.8% for premium cards
    public override decimal CalculateProcessingFee(decimal orderTotal)
    {
        decimal rate = _isPremiumCard ? 0.008m : 0.015m;
        return Math.Round(orderTotal * rate, 2);
    }

    public override string GetReceiptLabel()
    {
        string tier = _isPremiumCard ? "Premium" : "Standard";
        return $"{tier} Credit Card (ref: {AccountReference})";
    }
}

public class BankTransferPayment : PaymentMethod
{
    public BankTransferPayment(string sortCodeRef) : base(sortCodeRef) { }

    // Bank transfers are flat fee — not percentage-based
    public override decimal CalculateProcessingFee(decimal orderTotal)
    {
        return 0.25m;  // flat 25p regardless of order size
    }
    // Note: GetReceiptLabel() is NOT overridden — it uses the base default
}

public class CryptoPayment : PaymentMethod
{
    private readonly string _networkName;

    public CryptoPayment(string walletRef, string networkName) : base(walletRef)
    {
        _networkName = networkName;
    }

    // Crypto fees vary by network congestion — simulated here as 2%
    public override decimal CalculateProcessingFee(decimal orderTotal)
    {
        return Math.Round(orderTotal * 0.02m, 2);
    }

    public override string GetReceiptLabel()
    {
        return $"Crypto ({_networkName}) — wallet: {AccountReference}";
    }
}

class Program
{
    static void Main()
    {
        // The list holds the BASE TYPE — we don't care which concrete type is inside
        var checkoutPayments = new List<PaymentMethod>
        {
            new CreditCardPayment("VISA-4242", isPremiumCard: false),
            new CreditCardPayment("AMEX-0001", isPremiumCard: true),
            new BankTransferPayment("20-44-53"),
            new CryptoPayment("0xA1B2C3", "Ethereum")
        };

        decimal orderTotal = 150.00m;

        // Same call — PrintReceipt — but each payment type does its own thing
        foreach (PaymentMethod payment in checkoutPayments)
        {
            payment.PrintReceipt(orderTotal);
        }
    }
}
▶ Output
Standard Credit Card (ref: VISA-4242)
Order total : £150.00
Processing : £2.25
Grand total : £152.25

Premium Credit Card (ref: AMEX-0001)
Order total : £150.00
Processing : £1.20
Grand total : £151.20

Payment via BankTransferPayment (ref: 20-44-53)
Order total : £150.00
Processing : £0.25
Grand total : £150.25

Crypto (Ethereum) — wallet: 0xA1B2C3
Order total : £150.00
Processing : £3.00
Grand total : £153.00
🔥
Interview Gold:Interviewers love asking: 'What happens if you don't mark a method virtual but you try to override it?' The answer: you can use `new` to hide it, but you won't get polymorphic dispatch — calling through the base type reference will still call the base method. This is method hiding, not overriding, and it's a trap.

Interface-Based Polymorphism: Decoupling Without Inheritance Chains

Inheritance-based polymorphism is powerful, but it chains you to a single parent. C# only allows one base class. Interfaces solve this by letting completely unrelated types share a common contract without being family.

Interface polymorphism is how most real production code achieves flexibility. Dependency injection, unit testing with mocks, the Strategy pattern, plugin architectures — they're all interface polymorphism wearing different hats.

The rule of thumb: if you find yourself thinking 'these types need to be interchangeable, but they don't share a logical ancestor', reach for an interface. A PDF report and a CSV export have nothing in common as objects, but they're both exportable. An EmailNotifier and an SMSNotifier aren't related, but they're both notifiers.

With C# 8+ you also get default interface methods, which let you add behaviour to an interface without breaking all existing implementations. Use this carefully — it's a migration tool, not a design tool.

ReportExporter.cs · CSHARP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
using System;
using System.Collections.Generic;

// The contract — any type that implements this becomes 'exportable'
public interface IReportExporter
{
    string FormatName { get; }
    void Export(IEnumerable<string> reportRows, string destinationPath);

    // C# 8+ default interface method — provides fallback without breaking old implementors
    void PrintExportSummary(string destinationPath)
    {
        Console.WriteLine($"  [{FormatName}] Export complete → {destinationPath}");
    }
}

public class PdfExporter : IReportExporter
{
    public string FormatName => "PDF";

    public void Export(IEnumerable<string> reportRows, string destinationPath)
    {
        Console.WriteLine($"Generating PDF with {System.Linq.Enumerable.Count(reportRows)} rows...");
        // Real implementation would use a PDF library like iTextSharp
        PrintExportSummary(destinationPath);
    }
}

public class CsvExporter : IReportExporter
{
    public string FormatName => "CSV";
    private readonly char _delimiter;

    public CsvExporter(char delimiter = ',')
    {
        _delimiter = delimiter;
    }

    public void Export(IEnumerable<string> reportRows, string destinationPath)
    {
        Console.WriteLine($"Writing CSV (delimiter: '{_delimiter}') with {System.Linq.Enumerable.Count(reportRows)} rows...");
        PrintExportSummary(destinationPath);
    }
}

public class JsonExporter : IReportExporter
{
    public string FormatName => "JSON";

    public void Export(IEnumerable<string> reportRows, string destinationPath)
    {
        Console.WriteLine($"Serialising {System.Linq.Enumerable.Count(reportRows)} rows to JSON...");
        // Overrides the default summary to add JSON-specific detail
        Console.WriteLine($"  [JSON] Minified export → {destinationPath}");
    }

    // Override the default interface method with a custom version
    public void PrintExportSummary(string destinationPath)
    {
        Console.WriteLine($"  [JSON] Minified export → {destinationPath}");
    }
}

// This class only knows about IReportExporter — it's completely decoupled from PDF/CSV/JSON
public class ReportingService
{
    private readonly IReportExporter _exporter;  // depends on the interface, not the concrete type

    // The concrete exporter is injected — swap it without touching this class
    public ReportingService(IReportExporter exporter)
    {
        _exporter = exporter;
    }

    public void RunMonthlyReport()
    {
        var salesData = new List<string>
        {
            "January,North,£42,500",
            "January,South,£31,200",
            "January,East,£28,900"
        };

        Console.WriteLine($"Running monthly report using: {_exporter.FormatName}");
        _exporter.Export(salesData, "/reports/monthly-2024-01");
        Console.WriteLine();
    }
}

class Program
{
    static void Main()
    {
        // Swap the exporter — ReportingService never needs to change
        var services = new List<ReportingService>
        {
            new ReportingService(new PdfExporter()),
            new ReportingService(new CsvExporter(delimiter: ';')),
            new ReportingService(new JsonExporter())
        };

        foreach (var service in services)
        {
            service.RunMonthlyReport();
        }
    }
}
▶ Output
Running monthly report using: PDF
Generating PDF with 3 rows...
[PDF] Export complete → /reports/monthly-2024-01

Running monthly report using: CSV
Writing CSV (delimiter: ';') with 3 rows...
[CSV] Export complete → /reports/monthly-2024-01

Running monthly report using: JSON
Serialising 3 rows to JSON...
[JSON] Minified export → /reports/monthly-2024-01
⚠️
Pro Tip:When you use an interface as a constructor parameter (like `IReportExporter` above), you've just made your class mockable. In a unit test, pass in a fake exporter that doesn't touch the file system. This is why interface polymorphism is the foundation of testable code — not just a design pattern.

The `new` Keyword Trap: Method Hiding vs True Polymorphism

This is the gotcha that trips up developers who think they're overriding but are actually hiding. When you use the new keyword on a derived class method, you're not participating in polymorphism — you're creating a completely separate method that shadows the base class version at compile time.

The dangerous part? It compiles without errors. It looks like it works when you test it directly on the derived type. But the moment you reference the derived object through a base type variable — which is exactly what polymorphism requires — the base class method runs instead of yours. The runtime ignores your new method entirely.

This almost always happens by accident when someone forgets to mark the base method virtual and the compiler warns you to add new to suppress the warning. Adding new silences the warning but gives you hiding, not overriding. If you need true polymorphic dispatch, go back and add virtual to the base.

MethodHidingDemo.cs · CSHARP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
using System;

public class Notification
{
    // NOT marked virtual — this is the problem
    public string GetDeliveryChannel()
    {
        return "Base: Generic channel";
    }

    // This one IS virtual — safe for polymorphism
    public virtual string GetMessagePreview()
    {
        return "Base: Default message preview";
    }
}

public class PushNotification : Notification
{
    // 'new' hides the base method — does NOT participate in polymorphism
    public new string GetDeliveryChannel()
    {
        return "Derived: Push via APNs/FCM";
    }

    // 'override' replaces the base method — true polymorphism
    public override string GetMessagePreview()
    {
        return "Derived: Push preview — tap to open";
    }
}

class Program
{
    static void Main()
    {
        PushNotification pushDirect = new PushNotification();
        Notification pushedAsBase = new PushNotification();  // same object, base type reference

        Console.WriteLine("=== Called on derived type directly ===");
        Console.WriteLine(pushDirect.GetDeliveryChannel());  // calls the 'new' hidden method
        Console.WriteLine(pushDirect.GetMessagePreview());   // calls the overridden method

        Console.WriteLine();
        Console.WriteLine("=== Called through base type reference ===");
        // GetDeliveryChannel: hiding — base type reference calls BASE version, ignores 'new'
        Console.WriteLine(pushedAsBase.GetDeliveryChannel());
        // GetMessagePreview: override — base type reference still calls DERIVED version
        Console.WriteLine(pushedAsBase.GetMessagePreview());
    }
}
▶ Output
=== Called on derived type directly ===
Derived: Push via APNs/FCM
Derived: Push preview — tap to open

=== Called through base type reference ===
Base: Generic channel
Derived: Push preview — tap to open
⚠️
Watch Out:The compiler warning 'Method hides inherited member — use the new keyword if hiding was intended' is C#'s way of saying 'are you sure?'. Suppress it with `new` only when hiding is genuinely what you want. If you're confused, you almost certainly want `virtual` + `override` instead.
AspectCompile-Time (Overloading)Runtime (Override / Interface)
When resolvedAt compile time by the compilerAt runtime by the CLR
MechanismMultiple methods, same name, different signaturesvirtual/override or interface implementation
FlexibilityFixed at compile time — no swapping at runtimeBehaviour swaps based on actual object type at runtime
Primary use caseSame operation, different input shapes (e.g. Log(string) vs Log(Exception))Interchangeable implementations (payment types, exporters, strategies)
Testability impactMinimal — overloads are on concrete typesHigh — interfaces enable mocking and dependency injection
Risk of confusionLow — compiler catches wrong callsHigher — method hiding ('new') can silently break polymorphism
abstract keyword applicable?NoYes — forces every derived class to provide its own implementation

🎯 Key Takeaways

  • Polymorphism isn't syntax — it's a design decision. The payoff is that adding a new type (payment method, exporter, notification channel) means writing one new class, not editing existing ones.
  • Method hiding with 'new' compiles and runs but silently breaks polymorphism the moment you use a base-type reference — always check whether 'virtual' + 'override' was what you actually meant.
  • Interface-based polymorphism is the workhorse of real production code: it decouples consumers from implementations, makes unit testing with mocks possible, and enables dependency injection.
  • Abstract classes and interfaces serve different purposes: use abstract when there's genuinely shared state or partial behaviour across related types; use interfaces when you need a contract across unrelated types or want multiple contracts on one class.

⚠ Common Mistakes to Avoid

  • Mistake 1: Using 'new' thinking it overrides — Symptom: derived class method is never called when objects are stored in a base-type list or passed to a method accepting the base type. Fix: add 'virtual' to the base class method and use 'override' in the derived class. The 'new' keyword creates method hiding, not polymorphic dispatch.
  • Mistake 2: Calling an overridden method in a base class constructor — Symptom: the overridden method fires before the derived class constructor has run, so derived fields are still at their default values (null, 0, false), causing NullReferenceExceptions or wrong output. Fix: avoid calling virtual methods from constructors. Use a separate initialisation method or a factory pattern where the object is fully constructed before any virtual calls are made.
  • Mistake 3: Overloading based solely on return type — Symptom: compile error 'Type already defines a member called X with the same parameter types'. Fix: overload resolution in C# uses the method signature (name + parameter types/count), never the return type. If you need different return types, use different method names, generics, or out parameters.

Interview Questions on This Topic

  • QWhat is the difference between method overriding and method hiding in C#, and how does using a base-type reference expose the difference?
  • QCan you explain how the CLR decides which method implementation to invoke at runtime when virtual dispatch is involved — and what role the vtable plays in that process?
  • QIf a class implements two interfaces that both declare a method with the same signature, how does C# resolve the conflict, and how would you provide separate implementations for each interface?

Frequently Asked Questions

What is the difference between abstract and virtual in C#?

A virtual method has a default implementation in the base class that derived classes can override but don't have to. An abstract method has no implementation at all in the base class — every non-abstract derived class must override it or the code won't compile. You can only declare abstract methods inside abstract classes.

Can polymorphism work with interfaces in C# or only with inheritance?

Both work. Interface polymorphism is actually more common in modern C# because it doesn't lock you into a single inheritance chain. Any unrelated class can implement the same interface and be treated interchangeably. This is the foundation of dependency injection and the Strategy pattern.

Why does calling a virtual method in a constructor cause problems?

When a base class constructor calls a virtual method, the derived class's override runs — but the derived class constructor hasn't executed yet. Any fields the override depends on are still at their default values. This leads to NullReferenceExceptions or silently incorrect behaviour that's very hard to debug. Avoid virtual calls in constructors entirely.

🔥
TheCodeForge Editorial Team Verified Author

Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.

← PreviousInterfaces in C#Next →Abstract Classes in C#
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged