Method overloading in C# is a feature that allows you to define multiple methods with the same name in the same class but with different parameters. The compiler differentiates these methods by their signatures, which include the number of parameters, types of parameters, and the order of parameters. Method overloading increases the readability of the code by allowing the same method name to be used for different operations.
Basics of Method Overloading
Method overloading allows you to use the same method name with different parameters. This is useful when you want to perform similar operations in slightly different ways depending on the input.
Example
usingSystem;
classCalculator { // Method to add two integers publicintAdd(inta, intb) { returna+b; } // Overloaded method to add three integers publicintAdd(inta, intb, intc) { returna+b+c; } // Overloaded method to add two doubles publicdoubleAdd(doublea, doubleb) { returna+b; } }
classProgram { staticvoidMain() {
Calculatorcalc=newCalculator();
// Calling the method with two integers intsum1=calc.Add(2, 3); Console.WriteLine("Sum of two integers: "+sum1); //output- Sum of two integers: 5
// Calling the overloaded method with three integers intsum2=calc.Add(4, 5, 6); Console.WriteLine("Sum of three integers: "+sum2); //output- Sum of three integers: 15
// Calling the overloaded method with two doubles doublesum3=calc.Add(1.5, 2.5); Console.WriteLine("Sum of two doubles: "+sum3); //output- Sum of two doubles: 4 } }
Explanation of the Example
Class Definition: We define a class Calculator that contains overloaded Add methods.
The first Add method takes two integers as parameters and returns their sum.
The second Add method is overloaded to take three integers and return their sum.
The third Add method is overloaded to take two double parameters and return their sum.
Method Calls:
In the Main method, we create an instance of the Calculator class.
We call the Add method with two integers, which invokes the first method.
We call the overloaded Add method with three integers, which invokes the second method.
We call the overloaded Add method with two doubles, which invokes the third method.
Output:
The program prints the results of the three method calls, demonstrating that the appropriate overloaded method is called based on the parameters passed.
Advantages of Method Overloading
Improved Readability: Using the same method name for similar operations makes the code more intuitive and easier to understand.
Code Reusability: Overloaded methods can reuse the same logic with different input parameters, reducing code duplication.
Flexibility: Allows methods to handle different types of input and perform appropriate operations based on the input parameters.