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

  1. Methods must have the same name.

  2. Must have different parameter lists:

    • Different number of parameters

    • Different parameter types

    • Different order of parameter types

  3. 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

FeatureExample / Notes
Same method nameAdd(int a, int b)
Different number of parametersAdd(int a, int b, int c)
Different parameter typesMultiply(int, int) vs Multiply(double, double)
Different parameter orderPrint(string, int) vs Print(int, string)
Cannot overload by return typeint 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.