Method Overloading

Create different versions of the same method.

Overload a method

Sometimes, we might need to create a method that, depending on the type and number of parameters, will perform a slightly different set of actions.

Suppose we have a method called Multiply() that takes two numbers and multiplies them. What if we need the same method to accept not two, but three numbers?

That’s where method overloading comes into play.

Method signature

In C#, we can create several methods that have the same name but differ in other portions of its signature. Method signature consists of several parts:

  • Method name
  • Parameter quantities
  • Parameter types
  • Parameter order
  • Parameter modifiers

Note: Parameter names and the method’s return type aren’t part of the method signature.

Method overloading creates several methods that have the same name but differ in any other parts of the signature.

Consider the following example:

public double Multiply(int firstNumber, int secondNumber)
	return firstNumber * secondNumber;

public double Multiply(int firstNumber, int secondNumber, int thirdNumber)
	return firstNumber * secondNumber * thirdNumber;

The methods above have the same name but different signatures. In this example, the difference is based on the number of parameters.

In this case, the Multiply() method has two overloads.

We can visualize the method signatures as follows:

Multiply(int, int);
Multiply(int, int, int);

Depending on what parameters we use, the corresponding version of the method is called:

Get hands-on with 1200+ tech skills courses.