The source code to demonstrate method overloading based on the number of arguments is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to demonstrate method overloading based
//on the number of arguments
using System;
class MethodOver
{
static int Sum(int a, int b)
{
int r = 0;
r = a + b;
return r;
}
static int Sum(int a, int b, int c)
{
int r = 0;
r = a + b + c;
return r;
}
static int Sum(int a, int b, int c, int d)
{
int r = 0;
r = a + b + c+ d;
return r;
}
static void Main(string[] args)
{
int result = 0;
result = Sum(10, 20);
Console.WriteLine("Sum : " + result);
result = Sum(10, 20,30);
Console.WriteLine("Sum : " + result);
result = Sum(10, 20,30,40);
Console.WriteLine("Sum : " + result);
}
}
Output:
Sum : 30
Sum : 60
Sum : 100
Press any key to continue . . .
Explanation:
In the above program, we created a class MethodOver, here we overloaded the sum() method based on the number of arguments to calculate the sum of given arguments.
Here, we created the three methods to calculate the sum of given arguments and return the result to the calling method.
Now look to the Main() method. Here, we created the local variable result and then called each overloaded method one by one and printed the result on the console screen.
Program:
The source code to demonstrate method overloading based on the number of arguments is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class MethodOver, here we overloaded the sum() method based on the number of arguments to calculate the sum of given arguments.
Here, we created the three methods to calculate the sum of given arguments and return the result to the calling method.
Now look to the Main() method. Here, we created the local variable result and then called each overloaded method one by one and printed the result on the console screen.