C# Method Overloading
Method overloading lets you define multiple methods with the same name but different parameter lists (different number or types of parameters). The compiler picks the right one based on the arguments you provide.
Overloading is useful when you want to perform a conceptually similar operation on different types or numbers of inputs, like adding two integers versus adding two doubles.
static int Add(int a, int b) { }
static double Add(double a, double b) { }How overloading works
Methods can share a name if their parameter lists differ in number, order, or type. The return type alone is not enough to distinguish overloaded methods.
Choosing the right overload
The compiler matches the method call to the overload whose parameters best fit the arguments provided, considering implicit conversions where needed.
using System;
class Program {
static int Add(int a, int b) {
return a + b;
}
static double Add(double a, double b) {
return a + b;
}
static void Main() {
Console.WriteLine(Add(2, 3));
Console.WriteLine(Add(2.5, 3.5));
}
}5
6The compiler chooses the int version or the double version based on argument types.
using System;
class Program {
static void Print(string message) {
Console.WriteLine(message);
}
static void Print(string message, int times) {
for (int i = 0; i < times; i++) Console.WriteLine(message);
}
static void Main() {
Print("Hi");
Print("Hi", 2);
}
}Hi
Hi
HiThe second Print() overload accepts an extra parameter for repetition count.
Key points
- Overloaded methods share a name but differ in parameters.
- Return type alone cannot distinguish overloaded methods.
- The compiler picks the best-matching overload at compile time.
- Overloading improves readability by using one intuitive method name.
