You can have multiple methods with the same name โ as long as their parameters are different. That's method overloading. It keeps your code consistent and intuitive.
Same Name, Different Parameters
Overload by changing the number of parameters or their types. The compiler picks the right one based on what you pass.
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(3, 4));
Console.WriteLine(Add(2.5, 3.7));
}
}
Try it Yourself โ
Overloading by Number of Parameters
You can also overload by having a different number of parameters โ even if the types are the same.
using System;
class Program {
static int Multiply(int a, int b) {
return a * b;
}
static int Multiply(int a, int b, int c) {
return a * b * c;
}
static void Main() {
Console.WriteLine(Multiply(3, 4));
Console.WriteLine(Multiply(2, 3, 4));
}
}
Try it Yourself โ
Overloading with Different Types
The return type alone isn't enough to overload โ the compiler needs to see different parameters. But you can combine different types and counts freely.
using System;
class Program {
static string Format(string text) {
return "[" + text + "]";
}
static string Format(int number) {
return "(" + number + ")";
}
static string Format(string text, int times) {
string result = "";
for (int i = 0; i < times; i++) {
result += text;
}
return result;
}
static void Main() {
Console.WriteLine(Format("hello"));
Console.WriteLine(Format(42));
Console.WriteLine(Format("ha", 3));
}
}
Try it Yourself โ
Why Overload?
Overloading makes your API natural. Instead of AddInt, AddDouble, and AddThreeInts, you just have Add that works however you call it.
using System;
class Program {
static int Sum(int a, int b) {
return a + b;
}
static int Sum(int a, int b, int c) {
return a + b + c;
}
static int Sum(int[] numbers) {
int total = 0;
foreach (int n in numbers) {
total += n;
}
return total;
}
static void Main() {
Console.WriteLine(Sum(1, 2));
Console.WriteLine(Sum(1, 2, 3));
Console.WriteLine(Sum(new int[] {1, 2, 3, 4}));
}
}
Try it Yourself โ