C# Method Overloading

Method overloading lets you define several methods with the same name but different parameters. C# figures out which version to run based on the arguments you pass, so you can give related operations one memorable name instead of inventing a new name for every variation.

What is Method Overloading?

In C#, two or more methods can share the same name as long as their parameter lists are different. This is called method overloading. When you call the method, the compiler looks at the number and types of arguments you provide and picks the matching version automatically. It is a form of compile-time polymorphism, meaning the decision happens while your code is being built, not while it runs.

Overloading is useful when you want to perform the same logical action on different kinds of data. Instead of writing AddInts, AddDoubles, and AddStrings, you can write one method named Add that works with several parameter combinations.

Two methods, same name

static int PlusMethod(int x, int y)
{
    return x + y;
}

static double PlusMethod(double x, double y)
{
    return x + y;
}

static void Main()
{
    int myNum1 = PlusMethod(8, 5);
    double myNum2 = PlusMethod(4.3, 6.26);
    Console.WriteLine("int: " + myNum1);
    Console.WriteLine("double: " + myNum2);
}
// Output:
// int: 13
// double: 10.56

What Counts as a Different Signature

The compiler tells overloads apart using the method signature: the method name plus the number, types, and order of its parameters. Important rule for beginners: the return type is NOT part of the signature. You cannot create two methods that differ only by what they return.

Difference between methodsValid overload?
Different number of parametersYes
Different parameter typesYes
Different order of parameter typesYes
Only the return type is differentNo
Only a parameter name is differentNo

Overloading by parameter count

static void Greet(string name)
{
    Console.WriteLine("Hello, " + name + "!");
}

static void Greet(string name, int times)
{
    for (int i = 0; i < times; i++)
    {
        Console.WriteLine("Hello, " + name + "!");
    }
}

static void Main()
{
    Greet("Ava");
    Greet("Ben", 2);
}
// Output:
// Hello, Ava!
// Hello, Ben!
// Hello, Ben!
Note: A compiler error like 'cannot define overloaded method because it differs only by return type' usually means two of your methods have identical parameter lists. Change the parameters, not just the return type.

Overloading keeps your code clean and predictable. Callers only need to remember one name, and the compiler quietly routes each call to the right implementation based on the arguments supplied.

Exercise: C# Method Overloading

In C#, what must differ between two methods with the same name for them to be valid overloads?