Method overloading in C# is a feature that allows you to define multiple methods in a class with the same name but different parameters (either in number, type, or both). The compiler differentiates the methods based on the number and types of arguments passed to them when they are called.
Developer reuse the same method name for different operations, making the code more readable and easier to maintain.
Rules for Method Overloading
Same Method Name: All overloaded methods must have the same name.
Different Parameters: The methods must differ in the number or type of parameters.
Return Type: The return type can be the same or different, but it cannot be used to differentiate overloaded methods.
Overloading with Different Number of Parameters
You can overload a method by changing the number of parameters passed.
using System;
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
}
class MyExample {
static void Main(String[] args) {
Calculator calc = new Calculator();
Console.WriteLine(calc.add(10, 20)); // Calls the method with two integers
Console.WriteLine(calc.add(10, 20, 35)); // Calls the method with three integers
}
}
Output:
65
Explanation: The method add() is overloaded to accept either two or three int parameters.
Overloading with Different Data Types
You can overload methods with different data types.
Example:
using System;
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add two double values
public double add(double a, double b) {
return a + b;
}
}
class MyExample {
static void Main(String[] args) {
Calculator calc = new Calculator();
Console.WriteLine(calc.add(10, 20)); // Calls the method with two integers
Console.WriteLine(calc.add(10.5, 20.4)); // Calls the method with two doubles
}
}
Output:
30.9
Explanation: The method add() is overloaded to accept either integers or doubles.
Overloading Methods with Default Parameter Values
You can overload methods with different parameter values.
Example:
using System;
class Calculator {
// Method to add two integers
public int add(int a, int b=0) {
return a + b;
}
}
class MyExample {
static void Main(String[] args) {
Calculator calc = new Calculator();
Console.WriteLine(calc.add(10)); // Calls the method with single integer parameter
Console.WriteLine(calc.add(10, 20)); // Calls the method with two doubles
}
}
Output:
30
Explanation:
- In this example, the add() method has a default value for the parameter b. If the second argument is not passed, it defaults to 0.
- This allows for overloading based on the presence or absence of the second argument.