Polymorphism in C#
In this article, I am going to give you a brief introduction to Polymorphism in C#. Please read our previous where we discussed Abstract Class and Abstract Methods in C# with Examples. At the end of this article, you will understand the following polymorphism pointers in detail.
- What is Polymorphism?
- Why we need Polymorphism?
- Types of Polymorphism in C#?
- What is Compile-Time Polymorphism?
- What is Runtime Polymorphism?
Note: It is one of the primary pillars of object-oriented programming.
What is Polymorphism?
The word polymorphism is derived from the Greek word, where Poly means many and morph means faces/ behaviors. So, polymorphism means one thing having many (poly) form. Let’s have a look at the following diagram:
As shown in the above diagram, the vehicle is something that has various forms; two-wheeler, three-wheeler and four-wheeler and so on. So this is one example of polymorphism.
Technically we can say that when a function shows different behaviors when we passed different types and number values, then it is called polymorphism. So behaving in different ways depending on the input received is known as polymorphism i.e. whenever the input changes, automatically the output or the behavior also changes.
Types of Polymorphism in C#
There are two types of polymorphism in C#
- Static polymorphism / compile-time polymorphism / Early binding
- Dynamic polymorphism / Run-time polymorphism / Late binding
The following diagram shows different types of polymorphisms in C# with their examples.
The polymorphism in C# can be implemented using the following three ways.
What is Compile-Time Polymorphism?
In the case of compile-time polymorphism, the object of class recognizes which method to be executed for a particular method call at the time of program compilation and binds the method call with method definition.
This happens in case of overloading because in case of overloading each method will have a different signature and based on the method call we can easily recognize the method which matches the method signature.
It is also called as static polymorphism or early binding. Static polymorphism is achieved by using function overloading and operator overloading
What is Runtime Polymorphism?
In the case of Runtime Polymorphism for a given method call, we can recognize which method has to be executed exactly at runtime but not in compilation time because in case of overriding we have multiple methods with the same signature.
So, which method to be given preference and executed that is identified at Runtime and binds the method call with its suitable method. It is also called as dynamic polymorphism or late binding. Dynamic Polymorphism is achieved by using function overriding.
In the next article, I am going to discuss Function Overloading in C# with some real-time examples. Here, in this article, I try to explain what exactly Polymorphism in C# and their types and when to use Polymorphim in real-time application.