Conteúdo do 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
using System; class ConsoleApp { static int sum(int a, int b) { return a + b; } static int sum(int a, int b, int c) { return a + b + c; } static void Main() { Console.WriteLine(sum(5, 7)); Console.WriteLine(sum(5, 7, 9)); } }
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
static int sum(int a, int b) { return a + b; } // This is wrong and will show an error static long sum(int a, int b) { return a + b; }
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
sum(1, 3); // Should it execute `int sum(int a, int b)` or `long sum(int a, int b)` ? // It is impossible to reach a good answer for the compiler in this case so it shows an error
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
static int sum(int a, int b) { return a + b; } // This is wrong and will show an error static long sum(int first, int second) { return first + second; }
It is because the names of parameters don't matter but their types do. The following overloading cases are valid:
index
using System; class ConsoleApp { static int sum(int a, int b) { return a + b; } static long sum(long a, long b) { return a + b; } static string sum(int a, long b, float c) { return Convert.ToString(a + b + c); } static void Main() { Console.WriteLine(sum(5, 7)); // Calls 'int sum()' Console.WriteLine(sum(500000000000, 700000000000)); // Calls 'long sum()' Console.WriteLine(sum(5, 7, 9)); // Calls 'string sum()' } }
Obrigado pelo seu feedback!