C# ยท Chapter 27 of 46

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.

Syntax
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.

Example 1 (csharp)
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));
  }
}
Output
5
6

The compiler chooses the int version or the double version based on argument types.

Example 2 (csharp)
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);
  }
}
Output
Hi
Hi
Hi

The 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.
๐Ÿ’ก Note: Overloading is resolved at compile time, unlike overriding which is resolved at runtime through inheritance.

๐Ÿ“ Quick Quiz

1. What must differ between overloaded methods?

2. Can two methods be overloaded by return type alone?

3. When is the correct overload chosen?