Internals of Static Polymorphism

Polymorphism

If an entity is appearing with the same name in a given context in the various formats then the entity is said to be exhibiting polymorphism.

Types of Polymorphism

Polymorphism can be categorised into the following 2 types:

  1. Static polymorphism (or) compile time polymorphism (or) Early Binding
  2. Dynamic polymorphism (or) runtime polymorphism (or) Late Binding

Examples of Polymorphism

  1. Overloading is the best example of static polymorphism.
  2. Overriding is the best example of dynamic polymorphism.

Overloading

Overloading can be done using methods and constructors.

Method Overloading: If a method has the same name and with multile signatures in various 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:

  1. public class Test    
  2. {    
  3.     public static void Main(string[] args)    
  4.     {    
  5.         A a = new A();    
  6.         int r1=  a.M(10, 20, 30);    
  7.         int r2 = a.M(10, 20);    
  8.     }    
  9. }    
  10. public class A    
  11. {    
  12.     public int M(int x, int y)    
  13.     {    
  14.         return x + y;    
  15.     }    
  16.     
  17.     public int M(int x, int y, int z)    
  18.     {    
  19.         return x + y + z;    
  20.     }    
  21. }    
While compiling the code above the C# compiler will prepare a Class definition table and Method definition table, as shown below, by assigning a unique class id for each class and assigning a unique method id for each method. The Class ids and method ids will be added on top of each class definition and each method definition respectively as shown in the following diagram.

 

code Csharp compiler
 
During execution of a.M(10,20,30) the CLR will directly load the second method whose Mid=2. Since the C# compiler added a clear instruction to the CLR by adding a method Id value immediately after the code, the CLR will directly load the second method that has the Mid value equal to 2 into RAM for executing the code without any confusion. Since the C# compiler is giving clear instructions to the CLR about the method call, this type of polymorphism is called static polymorphism or Early Binding.