What is Polymorphism in C#

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

C# Tutorials

The object-oriented programming (OOP) paradigm has been in use since the past few decades. The key principles of Object-oriented programming are abstraction, encapsulation, inheritance, and polymorphism. This programming tutorial talks about OOP concepts, its benefits, and polymorphism, and illustrates the concepts through C# code examples.

What is Object Oriented Programming in C#?

Object-oriented programming (OOP) is based on the concept of objects — a collection of data and the functions that operate on them. These objects are self-contained, meaning they can exist independently of other objects. Objects have properties (data) and methods (functions or operations that operate on data), and they can be created, destroyed, and altered.

You can learn more about objects by reading our tutorial: What are Objects in C#?

OOP is a programming technique in which data structures consist of fields and methods interacting to build applications. OOP emphasizes data within an object rather than procedures or actions. This approach enables developers to create objects that model real-world entities, such as cars, trains, and houses.

OOP promotes reusability of code by enabling objects to inherit characteristics from other objects to reuse the same code. The origins of OOP can be traced back to Simula 67 – one of the first programming languages, developed in the year 1967, emphasizing classes and objects. The object-oriented programming paradigm was first brought to light by Alan Kay around the same time.

We discuss the concept of OOP in our tutorial: C# Object-oriented Programming for Beginners.

What is Polymorphism in C#?

Polymorphism is a technique in object-oriented programming that allows programmers to create objects that share the same interface but have different implementations. This means, instead of having different pieces of code – all of which accomplish the same task in different ways – you can have a single piece of code that can work with any object that implements a shared base class.

This can be useful when you want to write code that is agnostic to the specific type of object it is working with. As an example, assume that you have a class hierarchy consisting of a base class and two derived classes. The base class defines an abstract method, and the derived classes each provide their own implementations.

The word polymorphism derives from two Greek words. These words are poly meaning many and morphos meaning forms. Hence, a polymorphic object is one that can exist in many different forms at the same time. Although polymorphism is the same in all computer languages that support it, its implementation varies across languages.

You can learn more about classes by reading our tutorial: Introduction to Classes in C#.

Uses of Polymorphism in C#

Polymorphism can help developers write efficient, concise code and make your code maintainable, readable, reusable, and flexible when used correctly. Polymorphism lets you write code that will work on instances of different classes as long as they are derived from a common base class. It is a way of letting derived classes share implementations with a common base class.

Polymorphism enables more design flexibility by allowing many implementations of the same method to exist. With polymorphism, implementation and interface are separated, promoting code reuse and separating concerns.

Types of Polymorphism

Broadly, there are two forms of polymorphism: method overloading or parametric polymorphism, and method overriding or inclusion polymorphism. Method overloading (or parametric polymorphism) refers to the ability of a class to have multiple methods each having the same name but differing in their signatures. Method overriding (or inclusion polymorphism) is the ability of a base class to have a method whose implementation varies from one subclass to another.

How to Implement Polymorphism in C#

The most common use of polymorphism in C# is through inheritance, where a base class can be inherited by multiple derived classes. You can also implement compile-time or static polymorphism using method overloading.

Method Overloading, Compile-time Polymorphism, Early Binding, or Parametric Polymorphism

Constructor overloading and Operator overloading are typical examples of compile-time polymorphism. To implement compile-time polymorphism, developers can create a class that has two or more overloaded methods. Consider the following piece of example code, which illustrates polymorphism using method overloading in C#:

public class FileManager
{
    public void Write(string message)
    {
        Console.WriteLine("Inside Write method having one parameter.");
    }

    public void Write(string message, bool close)
    {
        Console.WriteLine("Inside Write method having two parameters.");
    }
}

You can use the following piece of C# code to invoke the Write() method of the FileManager class that accepts a string as a parameter, as shown below:

FileManager fileManager = new FileManager();
fileManager.Write("This is a text message");

Read: The Top Task Management Software for Developers

Method Overriding, Runtime Polymorphism, Late Binding, or Inclusion Polymorphism

Consider the following piece of code that shows two classes – a base class named Base and a derived class named Derived to demonstrate polymorphism through inheritance or runtime polymorphism:

public class Base
{
    public virtual void Display()
    {
        Console.WriteLine("Inside Base.");
    }
}
public class Derived: Base
{
    public override void Display()
    {
        Console.WriteLine("Inside Derived.");
    }
}

The Base class contains a virtual method named Display, which is overridden in the class named Derived.

Create an instance of Derived using a reference of the Base class. When you invoke the Display method using this instance, the Display method of the Derived class will be called:

Base obj = new Derived();
obj.Display();

However, if the Display method is not virtual in the Base class, the Display method of the Base class will be called.

Virtual methods are used to override the functionality of a base class method. When you create a derived class, you can override any virtual method in your base class by creating an equivalent method in your derived class with the same signature (name and parameters).

When an object is created at run time, it is said to be created dynamically, because the object type cannot be determined until runtime. Virtual methods are also used to call a base class method from within your derived classes.

Note that, while an interface provides another way to define one or more methods that have their implementations in the derived classes, you cannot use interfaces to implement dynamic polymorphism or late binding; late binding or runtime polymorphism can only be implemented using virtual methods.

Final Thoughts on Polymorphism in C#

Polymorphism is integral to any object-oriented language like C# or Java. Polymorphic classes are all “base” classes since they provide a base set of functionalities from which you can create one or more derived classes.

When you use polymorphism, you can swap out (or substitute) one class with another that implements the same base type and keep working on your application as if nothing has changed.

Read more C# programming tutorials and software development guides.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read