Method Overloading in C#

Introduction

Before start "Method Overloading" lets understand the base concept behind this.

Method overloading is part of Polymorphism. Polymorphism is one of the most important pillar of OOPs in c#.  
Polymorphism is of 2 types as Fig-1.
  • Compile time Polymorphism
  • Run time Polymorphism
Lets Get Started

See the below image(Fig-1).

Fig-1








Compile time polymorphism is called Method overloading where as Run time polymorphism called Method Overriding.


Here we will discuss about Method Overloading.

Method overloading is nothing but the same method  name having different signature.
Lets understand the above point.

Lets take an example.


Fig-2

See the Fig-2 when we tried to add two method with the same name then c# compiler can not find out which method to call. That is the reason why we got compilation error. 
Now To solve this we can implement "Method Overloading" by applying different signature.
Lets see this in action.

see the below Code

  class MyPolymorphism
{
        public void Addition(int val1,int val2,int val3)
        {

        }
        public void Addition(int val1,int val2)
        {

        }
    }
    

We can see even though we have same method name we did not get any compile time error.This is called Method overloading.

Lets take another example.

What happen when we take same method name , same signature(same parameter) but different return type.
Lets see in action.

Fig-3


In Fig-3 we can see method define have different type (highlighted one) and The variable name are in different position. But still we get compilation error.


what happen when Method name are same, signature contains same parameter but the parameter interchange there position in two methods.

Lets see in Action.

class MyPolymorphism
    {
        public void Addition(int val1,string val2)
        {
           
        }
        public void Addition(string val1,int val2)
        {

        }
    }

See the above code.
We interchange the parameter where as method name is same.

Its working fine...............
see the below Image. Build succeed.
Fig-4
What happen when method name  and parameter type are same and are placed in same order. But we append out parameter to it.

Lets see in action.

Fig-5

See the above Image . It works as build succeed even though the parameter are in same order and method name are same. Only Parameter return type is different.


Conclusion
I hope concept of method overloading is cleared.
Remember the below points while implementing the method overloading.

  • Method name should be same.
  • Do not apply the same signature(same type in same order).
  • Return type is not the part of  a method signature.
  • You can apply method overloading by interchanging the method parameter having different type.

Share:

No comments:

Post a Comment

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts