Method overloading means having different methods with same name but with different types of parameters or number of parameters also known as static polymorphism. In this article we will try to understand what is method overloading and how we can overload a method with example.
Suppose we have a class Calculate which can have a method Add by using two integers, two double, any number of integer, any number of double etc. so let’s see it in action by creating the customer class
public class Calculate
{
public Int32 Add(Int32 num1, Int32 num2)
{
return num1 + num2;
}
//Now create another method with same name Add but with two double
public double Add(double dbl1, double dbl2)
{
return dbl1 + dbl2;
}
//Create another method to accept array of integer and return long
public long Add(Int32[] numbers)
{
long result = 0;
for (Int32 i = 0; i < numbers.Length; i++)
result += numbers[i];
return result;
}
//Create a method to accept array of double and return double
public double Add(double[] doubles)
{
double result = 0;
for (Int32 i = 0; i < doubles.Length; i++)
result += doubles[i];
return result;
}
}
Now we will test our class one by one
class Program
{
static void Main(string[] args)
{
Calculate cal = new Calculate();
Int32 twoNumberResult = cal.Add(10, 20);
Console.WriteLine(twoNumberResult); // It will print 30
double twoDoubleResult = cal.Add(10.25, 20.30);
Console.WriteLine(twoDoubleResult); // It will print 30.55
Int32[] intArray = { 10, 20, 30, 40, 50 };
long intArrayResult = cal.Add(intArray);
Console.WriteLine(intArrayResult); // It will print 150
double[] doubleArray = { 10.11, 20.22, 30.33, 40.44, 50.55 };
double doubleArrayResult = cal.Add(doubleArray);
Console.WriteLine(doubleArrayResult); // It will print 151.65
Console.ReadLine();
}
}
If you want to test the above code just create a console application and copy and page the code and run it.
Let's see when we can overload a method when to not.
We can overload a method
- With different types of parameter
- with different number of parameter
- with same number of parameter but of different type
- with same number and type of parameter but in different sequence
We can not overload a method
- with different return type only
- with different access modifier only say (public, private, protected etc.)
- with regular and optional parameter
No comments:
Post a Comment