Letβs go over method overloading in C# β a powerful way to give multiple methods the same name but different behaviors.
π 1. What is Method Overloading?
Method overloading is when you define multiple methods with the same name but different parameter lists within the same class.
-
The compiler determines which method to call based on the number, type, or order of parameters.
-
Return type alone cannot distinguish overloaded methods.
π 2. Rules for Overloading
-
Methods must have the same name.
-
Must have different parameter lists:
-
Different number of parameters
-
Different parameter types
-
Different order of parameter types
-
-
Cannot overload based only on return type.
π 3. Examples
Overloading by Number of Parameters
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(2, 3)); // 5
Console.WriteLine(calc.Add(2, 3, 4)); // 9
Overloading by Parameter Type
public class Calculator
{
public int Multiply(int a, int b) => a * b;
public double Multiply(double a, double b) => a * b;
}
// Usage
Calculator calc = new Calculator();
Console.WriteLine(calc.Multiply(2, 3)); // 6
Console.WriteLine(calc.Multiply(2.5, 3.2)); // 8.0
Overloading by Parameter Order
public class Printer
{
public void Print(string text, int copies)
{
Console.WriteLine($"Printing '{text}' {copies} times");
}
public void Print(int copies, string text)
{
Console.WriteLine($"Printing '{text}' {copies} times (alternate)");
}
}
π 4. Important Notes
-
Overloading improves code readability by keeping similar operations under one method name.
-
Use overloading judiciously; too many variations can confuse users.
-
Overloading works at compile time (resolved by the compiler).
π 5. Summary Table
Feature | Example / Notes |
---|---|
Same method name | Add(int a, int b) |
Different number of parameters | Add(int a, int b, int c) |
Different parameter types | Multiply(int, int) vs Multiply(double, double) |
Different parameter order | Print(string, int) vs Print(int, string) |
Cannot overload by return type | int Foo() vs double Foo() β |
β Tip:
-
Method overloading is especially useful in constructors and utility classes.
-
Keeps APIs intuitive: e.g.,
Console.WriteLine
is heavily overloaded for different types.