Contenido del Curso
C# Beyond Basics
C# Beyond Basics
Method Overloading
Method overloading in C# allows you to define multiple methods with the same name in a class, each differing in their parameter types, parameter count, or both, providing a cleaner and more adaptable way to handle various input scenarios.
For-example, we can have a two methods with the same name but different number of parameters:
index
In the above code the sum
method was overloaded to have two variations of parameters. A method can also have different return types for different variations of itself however it is important for it to have no ambiguity otherwise the compiler will show an error because the primary way for a compiler to distinguish between two methods of the same name is their parameter list.
For-example:
index
The code above is wrong because the parameters are exactly the same as the original method while the return type is different, this is not allowed since it makes it impossible for the compiler (or even for humans) to choose which one to execute when the method is called:
index
This is why, when overloading a method, a method that has a different return type should also have a different set of parameters to make it distinguishable and remove ambiguity. The following is also wrong:
index
It is because the names of parameters don't matter but their types do. The following overloading cases are valid:
index
¿Todo estuvo claro?