Tuesday, April 5, 2016

Advantages of method Overloading in C#.Net Or When/Why to Use Method Overloading in C#.Net

Advantages of method Overloading in C#.Net Or  When to Use Method Overloading in C#.Net Or Why to Use Method Overloading in C#.Net 


Suppose you get one program to create a method which can do sum of two numbers, three numbers & four numbers by passing parameters.

So you will end up writing following methods,


Public void SumTwoNumbers(int a, int b)
{
}

Public void SumThreeNumbers(int a, int b, int c)
{
}

Public void SumFourNumbers(int a, int b, int c, int d)
{
}

And what if, if program ask you to do sum of upto 20 numbers, so you will end up with writing 20 different methods, and most worst task is the user who will use your program he/she might needs to use remember all the methods name.

So to overcome this scenario microsoft indroduces Method overloading.

So in this case you will write 20 methods with the same name but having different method signature, so here user don’t need to remember all the methods name, he just need to remember single method name as sum.

Also the example explains above contains only sum of integer number only and what if it should allow flaot and double numbers too. so in this case you have to remember many methods name, but in case of method overloading you just need to remember one name, so visual studio intelligence show you all the overloaded methods as below,




So in short,

=> It improves code readability & re-usability.

=> Save efforts & memory (it will save only one method name in memory instead of all methods like sumoftwonumbers etc)





  


7 comments:

  1. Hi,
    For the mentioned example, instead of overloading and creating 20 methods (you mentioned) why can't you use a single method and a params array - which can hold array of homogeneous elements.?

    something like

    public int add(params int[] nos)
    {
    return nos.Sum();
    }

    ReplyDelete
    Replies
    1. I agree, but what if user wants add mixed data type numbers (e.g int & float add, float & double etc) so in this case param array wont worked.

      Also we have option to use single method with optional parameters, but the concept of optional parameter came in .Net 4.0 onwards & its also have its advantage and disadvantage.

      Regards,
      Jatin

      Delete
  2. Good post. An alternative example could be something like "need a function to search a variety of data types for the number of times a word occurs". You might have an overload that looks something like:

    public int WordCount(XmlDocument doc) {
    ...
    }

    public int WordCount(String doc) {
    ...
    }

    public int WordCount(HTMLDocument doc) {
    ...
    }

    This is an example of where the exact same behavior needs to be executed against a number of varying parameter types.

    ReplyDelete
    Replies
    1. @clinton stevens: Thanks & alternative example is too good.

      Delete