Method overloading allows you to have multiple definitions of the same function name in the same scope. Function definitions must differ in the type and/or number of parameters in the parameter list.
Let's look at an example. Here, the call goes to a method with a single parameter -
using System; class Student { static void DisplayMarks(int marks1 = 90) { Console.WriteLine("Method with one parameter!"); } static void DisplayMarks(int marks1, int marks2 = 95) { Console.WriteLine("Method with two parameters!"); } static void Main() { DisplayMarks(97); } }
Now let's see what causes an ambiguous call. The confusion here is that the second method requires two default parameters, while the first method requires one parameter to be defaulted. This creates ambiguity.
using System; class Student { static void DisplayMarks(int marks1 = 90, int marks2 = 80) { Console.WriteLine("Method with two parameters!"); } static void DisplayMarks(int marks1, int marks2 = 80, marks3 = 98) { Console.WriteLine("Method with three parameters!"); } static void Main() { DisplayMarks(80); } }
The above is the detailed content of Overloaded methods and ambiguity in C#. For more information, please follow other related articles on the PHP Chinese website!