Language: EN

csharp-sobrecarga-funciones

What is function overloading in C#

Function overloading is a feature in C# that allows us to define multiple versions of methods with the same name, but 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 a single method to adapt to different scenarios.

Overloading Syntax

To use function overloading, the different versions of the function must have different arguments. That is, they must accept different types and/or quantities 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;
}

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

  • One for summing two integers
  • Another for summing three integers
  • Another for summing 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)
{
}

Practical Examples