Lesson 28 +10 XP

Method Overloading

Method Overloading

With method overloading, multiple methods share the same name but have different parameters.

Same name, different signature

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

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

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

Why overload?

You have one method name that works with different types or different numbers of arguments. C# picks the right version based on the arguments you pass.

The rule

The methods must differ in the number of parameters, the types of parameters, or both. The return type alone is not enough to distinguish overloads.

// Valid overloads - different parameter counts/types
int Add(int a, int b) => a + b;
int Add(int a, int b, int c) => a + b + c;
double Add(double a, double b) => a + b;

Overloading vs overriding

  • Overloading: same name, different parameters, in the same class.
  • Overriding: reimplementing a base class method in a subclass (you'll see this in the OOP module).

TL;DR

  • Overloading = same method name, different parameters.
  • C# chooses the matching version from your arguments.
  • Distinguish by parameter count/types, not return type.