Method Overloading
Defines what method overloading is and how it is used in programming
In C#, we can define multiple methods with same name but different arguments (parameters). This is called method overloading.
Consider a situation where we need to define two methods. The first method will perform the addition of two integers and the second method will perform the addition of three integers. We can define the methods as:
class AddClass { public void AddTwo(int n1, int n2) { Console.WriteLine("The sum is {0}", n1 + n2); }
public void AddThree(int n1, int n2, int n3) { Console.WriteLine("The sum is {0}", n1 + n2 + n3); } }
The AddTwo() method takes two integer arguments and displays their sum. Similarly, the AddThree() method takes three integer arguments and displays their sum. We call the methods as shown below:
AddClass a1 = new AddClass(); a1.AddTwo(2, 3); a1.AddThree(2, 3, 4);
Since both the methods are essentially performing the same function (addition), we can define them with same name. Let us modify the method definitions:
class AddClass { public void Add(int n1, int n2) { Console.WriteLine("The sum is {0}", n1 + n2); } public void Add(int n1, int n2, int n3) { Console.WriteLine("The sum is {0}", n1 + n2+n3); } }
Notice that both methods have the same name - Add. However, we will not get any error because the arguments of the methods are different. The first Add() method takes two integer arguments and the second Add() method takes three integer arguments. This is the important part of method overloading - the arguments of the overloaded methods should be different, either in numbers or in types. In our example, both methods take integer arguments but the number of arguments are different - the first Add() method takes two argument while the second Add() method takes three arguments. Hence, the overloading is valid.
When an overloaded method is called, the program checks the arguments passed to it. Then it calls the method with the matching argument:
AddClass a1 = new AddClass(); a1.Add(2, 3); a1.Add(2, 3, 4);
In the first method call, we have specified two arguments, so the Add() method with two integer arguments will be called. In the second method call, we have specified three arguments, so the Add() method with three integer arguments will be called.
Method overloading is mostly used in situations where we need to define multiple methods that take different arguments but perform the same type of operation. If the methods perform very different operations then there is no point in overloading them (we don't want to overload Add() method if one of the Add() method is actually performing multiplication of numbers!).