Polymorphism
If an entity is appearing with the same name in a given context in the different formats, then the entity is said to be exhibiting polymorphism.
Types of Polymorphism
Polymorphism can be categorised into 2 types:
- Static polymorphism (or) compile time polymorphism (or) Early Binding
- Dynamic polymorphism (or) run time polymorphism (or) Late Binding
Examples for Polymorphism
- Overloading is the best example for static polymorphism.
- Overriding is the best example for dynamic polymorphism.
Overloading
Overloading can be achieved by using methods and constructors.
Method Overloading: If a method is appearing with the same name and with different signature in different formats then the method is said to be overloaded (Method Signature is a combination of method name and the parameter types).
Method Overloading Sample Code
While compiling the below code, C# compiler will prepare Class definition table and Method definition table as shown below, by assigning unique class id for each class and assigns unique method id for each method. The class id's and method id's will be added on top of each class definition and each method definition respectively as shown in the following diagram:
public class Test
{
public static void Main(string[] args)
{
A a = new A();
int r1= a.M(10, 20, 30);
int r2 = a.M(10, 20);
}
}
public class A
{
public int M(int x, int y)
{
return x + y;
}
public int M(int x, int y, int z)
{
return x + y + z;
}
}
Why Overloading is Called as Static Polymorphism
During execution of a.M(10,20,30) clr will directly load second method whose Mid=2. Since C# compiler added a clear instruction to the CLR by adding method Id value immediately after the code, CLR will directly load second method which has Mid value equal to 2 into the RAM for executing the code without having any confusion. Since C# compiler is giving clear instructions to the CLR about the method call, this type of polymorphism is called as Static polymorphism or Early Binding.