Click here to Skip to main content
15,896,557 members
Articles / Programming Languages / C#
Tip/Trick

Internals of Static Polymorphism

Rate me:
Please Sign up or sign in to vote.
4.83/5 (4 votes)
10 May 2014CPOL1 min read 11.7K   3  
Internals of static polymorphism

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:

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

Examples for Polymorphism

  1. Overloading is the best example for static polymorphism.
  2. 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:

C++
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

Image 1

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Palle Technologies
India India
I am having 10 yrs of experience in Microsoft technologies . Currently working for palle technologies as a solutions architect .
I write articles ,c# interview questions and answers and sql interview questions and answers in skillgun, and also responsible for providing .net training in bangalore to palle technologies students .

Comments and Discussions

 
-- There are no messages in this forum --