Method overloading is very useful function found in C#, basically, it means we can have multiple methods with same name, but with different parameters. For example, the Console.WriteLine()
method in C# is overloaded and have 19 methods with same but different parameters to choose from.
Method overloading is one of the ways that C# implements polymorphism.
Let's take a look at an example, where we are creating calculator and need to add two integers or two double
using System;
public class OverloadingInCsharpProgram
{
public static void Main()
{
Overloading obj = new Overloading();
int twoNumberResult =obj.Add(10,20);
Console.WriteLine(twoNumberResult); // will print 30
double twoDoubleSum = obj.Add(15.25, 20.30);
Console.WriteLine(twoDoubleSum); // will print 35.55
int[] intArray = { 10, 20, 30, 40, 50 };
long intArrayResult = obj.Add(intArray);
Console.WriteLine(intArrayResult); // will print 150
}
public class Overloading
{
//method 1 with simple int parameters to add int's
public int Add(int num1, int num2)
{
return num1 + num2;
}
//another method with same name Add but with two double as parameter
public double Add(double dbl1, double dbl2)
{
return dbl1 + dbl2;
}
// another method to accept array of integer and return long but with same name
public long Add(int[] numbers)
{
long result = 0;
for (Int32 i = 0; i < numbers.Length; i++)
result += numbers[i];
return result;
}
}
}
Output:
30
35.55
150
As you can see in the above example, we have multiple methods with same name "Add
" but all methods have different parameter type, like method 1, Add(int num1, int num2), takes 2 integer values, while second Add method takes 2 double values and third one takes an array.