Polymorphism in C#
In this article, I am going to discuss Polymorphism in C#. Please read our previous article before proceeding to this article where we discussed Abstract Class and Abstract Methods in C# with Examples. In this article, we are going to discuss the following pointers
- What is 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.
We can implement polymorphism in C# using the following three approaches.
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 with 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 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 and hiding 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.