Method overloading

Several methods can share a name if their parameter lists differ. The compiler picks one from the argument types.

Time resolved at compile timeSpace O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Overload choice happens when the code is compiled, using the declared types of the arguments. That is the opposite of overriding, where the choice is made at run time from the real object.

Code

class Printer {
    public void Print(int x) => Console.WriteLine("int " + x);
    public void Print(double x) => Console.WriteLine("double " + x);
    public void Print(string x) => Console.WriteLine("string " + x);
    public void Print(object x) => Console.WriteLine("object " + x);
}

var p = new Printer();
p.Print(5);
p.Print(2.5);
p.Print("hi");
object boxed = 5;
p.Print(boxed);   // chosen by the variable's type, not the value inside

Tips

In the .NET library

Console.WriteLine itself has 18 overloads. Optional parameters (int retries = 3) often replace a pile of overloads.