Labs ICT
โญ Pro Login

Method Overloading

Method overloading lets you have multiple methods with the same name but different parameters. This sounds confusing at first, but it actually makes your code more intuitive.

What Is Method Overloading?

Imagine you want a method that adds two numbers. But you need it to work with integers, doubles, and maybe even strings. Instead of creating three different method names, you can overload the same method:

int Add(int a, int b)
{
    return a + b;
}

double Add(double a, double b)
{
    return a + b;
}

string Add(string a, string b)
{
    return a + b;
}

// C# figures out which one to call based on the arguments
Console.WriteLine(Add(5, 3));           // 8 (calls the int version)
Console.WriteLine(Add(2.5, 3.7));      // 6.2 (calls the double version)
Console.WriteLine(Add("Hello ", "World"));  // Hello World (calls the string version)

The key thing to understand is that C# determines which method to call based on the number, type, and order of the arguments you pass. This is called compile-time polymorphism.

Rules for Overloading

You cannot overload methods just by changing the return type. The parameters must be different:

// These will cause errors:
int Add(int a, int b) { return a + b; }
double Add(int a, int b) { return a + b; }  // ERROR โ€” same parameters!

// This is fine โ€” different parameter count:
int Add(int a, int b) { return a + b; }
int Add(int a, int b, int c) { return a + b + c; }

// This is also fine โ€” different parameter types:
void Print(int value) { Console.WriteLine(value); }
void Print(string value) { Console.WriteLine(value); }

The compiler uses the parameter list to figure out which method you are calling. If two methods have the same name and the same parameter list, the compiler gets confused and throws an error.

Why Is This Useful?

Overloading makes your API more intuitive. Instead of remembering different method names like AddInt, AddDouble, AddString, you just remember Add and let C# figure out the rest.

You will see overloading everywhere in C# libraries. For example, Console.WriteLine() itself is overloaded โ€” it can accept a string, an int, a boolean, or any other type because Microsoft wrote multiple versions of it.

๐Ÿงช Quick Quiz

What is method overloading?