csharp-sobrecarga-funciones

What is function overloading in C#

  • 4 min

Function overloading is a feature in C# that allows us to define multiple versions of methods with the same name, but with different parameters.

The C# compiler determines which version of the method should be invoked based on the arguments provided during the call.

This provides flexibility and improves code readability by allowing the same method to adapt to different scenarios.

If you want to learn more, check out the Introduction to Programming Course

Overloading Syntax

To use function overloading, the different versions of the function must have different arguments. That is, they must receive different types and/or numbers of parameters.

// Sum of two integers
public int Sumar(int a, int b)
{
	return a + b;
}

// Sum of three integers
public int Sumar(int a, int b, int c)
{
	return a + b + c;
}

// Sum of two floating-point numbers
public double Sumar(double a, double b)
{
	return a + b;
}
Copied!

In this example, the Sumar method is overloaded three times:

  • One to add two integers
  • Another to add three integers
  • Another to add two floating-point numbers.

It is not possible to use overloading based on the return type of the function. Only the parameters are involved.

For example, the following case, where we have two MiMetodo with the same number of parameters but different return, is not valid.

public int MiMetodo(int a, int b)
{
}

// this cannot be done
public double MiMetodo(int a, int b)
{
}
Copied!

Practical Examples

These examples are intended to show how to use overloading. It does not mean it is the best way to solve the problem they address. Usually, there are better alternatives.