Overloaded method and ambiguity in C#

CsharpProgrammingServer Side Programming

With method overloading, you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.

Let us see an example. In this the call would go to the method with a single parameter −

Example

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 us see what creates an ambiguous call. Here the confusion is that the second method would need two arguments as defaults, whereas the first methid needs one argument to be defaulted. This creates ambiguity.

Example

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);
   }
}
raja
Published on 14-Aug-2018 09:47:31
Advertisements