Method Overloading in C# with Example

Method Overloading in C# with Example
Method Overloading in C# with Example

We know very well how to create methods in C#.  We basically create methods to increase the code reusability.  Suppose if you want to add 2 numbers, you can create a method by the name of add_number with 2 parameters of type integer.  Same goes in case of adding or concatenating 2 strings, you can create a method by the name of add_string with 2 parameters of type string.  If you have a large number of methods like this in your project, it will be pretty much cumbersome to remember the name of each and every method, which eventually perform a same job, but only differ in signature and method name.  Signature of the method includes number of parameters, data type of parameter, and parameter modifier like out, ref.

To make the job easier, we make use of Method Overloading.  Method overloading will give you the ability to have multiple methods with same name, but with different signature.  Signature of the method does not include method return type and params parameter modifier, so you cannot overload any method based on that.  For the above given example, you can easily create 2 Add methods, one which will have 2 parameters of integer type and another one which will have 2 parameters of string type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{     

    class Program
    {
        static void Main(string[] args)
        {
            //Calling both the methods
            add(10, 20);
            add("Hello ", "World");

        }

        //First Method
        public static void add(int n1, int n2)
        {
            Console.WriteLine("Number: {0}", n1+n2);
        }

        //Second Method
        public static void add(string s1, string s2)
        {
            Console.WriteLine("String: {0}", s1 + s2);
        }
    }
}

 Output:

Number: 30
String: Hello World