find and solve || findandsolve.com
Please wait.....

C# Method Overloading

In the c#, Method overloading allows programmers to use multiple methods with the same name but different signatures. In a class you can implement two or more then two methods with the same name. This type of method depend based on the number and type of parameter passed as arguments to the methods.

Method overloading can be done by changing:  

  • By changing number of parameters in a method
  • By changing the order of parameters in a method
  • By using different data types for parameters

By changing number of parameters in a method

using System;
public class Program
{
  // adding two integer values.
    public int AddNumber(int a, int b)
    {
        int sum = a + b;
        return sum;
    }
    // adding three integer values.
    public int AddNumber(int a, int b, int c)
    {
        int sum = a + b + c;
        return sum;
    }     // Main Method
    public static void Main(String[] args)
    {
        // Creating Object
        Program ob = new Program();
        int sum = ob.AddNumber(11, 22);
        Console.WriteLine("sum of the two "+ "integer value : " + sum);
        int anotherResult = ob.AddNumber(10, 20, 30);
        Console.WriteLine("sum of the three " + "integer value : " + anotherResult);
    }
}

Output

sum of the two integer value : 33

sum of the three integer value : 60

By changing the order of parameters in a method

using System;
public class Program
{
  // Method
    public void StudentDetails(string name, int id)
    {
       Console.WriteLine("Name1 : " + name + ", "+ "ID1 : " + id);
    }
    // Method
    public void StudentDetails(int id, string name)
    {
      Console.WriteLine("Name2 : " + name + ", " + "ID2 : " + id);
    }
    // Main Method
    public static void Main(String[] args)
    {
        // Creating Object
        Program obj = new Program();
        obj.StudentDetails("Sylvia",141);
        obj.StudentDetails(145, "Alina");
    }
}

Output  

Name1 : Sylvia, ID1 : 141

Name2 : Alina, ID2 : 145

By using different data types for parameters

using System;
public class Program
{
   // adding three integer values.
    public int AddNumber(int a, int b, int c)
    {
        int sum = a + b + c;
        return sum;     }
    // adding three double values.
    public double AddNumber(double a,double b, double c)
    {
        double sum = a + b + c;
        return sum;
    }
    // Main Method
    public static void Main(String[] args)
    {
        // Creating Object
        Program obj = new Program();
        int sum = obj.AddNumber(11, 22, 33);
        Console.WriteLine("sum of the three "+ "integer value : " + sum);
        double sum1 = obj.AddNumber(7.0, 3.0, 9.0);
        Console.WriteLine("sum of the three "+ "double value : " + sum1);
    }
}

Output

sum of the three integer value : 66

sum of the three double value : 19