Polymorphism is one of the pillars of C# Object Oriented Language. Poly means many and morphism means forms, it means having many forms.
In real life, how a kid behaves like a student in school and the same kid behaves like a son or daughter to his or her parents and the same behaves as a grandson or granddaughter to his or her grandparents.
Similarly, in an object-oriented programming language, the same method behaves in many forms based on the usage. It is mostly used during inheritance as there are classes related to each other.
We can divide mainly into 2 types:
- Compile Time Polymorphism
- Run Time Polymorphism
This is called function overloading, in this case, there are functions more than one having the same name but with different parameters. Here the compiler can understand
which function is going to execute based on the function call signature. As it is happening at compile-time, it is called Compile Time Polymorphism.
Example 1: A simple example without inheritance.
The output will be:
Example 2: An Example with inheritance.
The output will be:
This is called function overriding, in this case, there are functions more than one having the same name and same parameters but uses virtual and override keywords. Here the compiler cannot understand which function is going to execute until execution (runtime). As it is happening at run time, it is called Run Time Polymorphism. Runtime polymorphism can happen only during inheritance.
Example 3: An Example with inheritance using virtual in parent and override in child class to override the
parent class method behavior.
The output will be: