Method Overloading in C#

Method overloading permits multiple methods in the same class to have the same name as long as they have unique signatures. When compiling an invocation of an overloaded method, the compiler uses overload resolution to determine the specific method to invoke.
Overload resolution finds the one method that best matches the arguments or reports an error if no single best match can be found. The following example shows overload resolution in effect.
The comment for each invocation in the Main method shows which method is actually invoked.

Code Snippet
  1. class Test
  2. {
  3.     static void F()
  4.     {
  5.         Console.WriteLine("F()");
  6.     }
  7.     static void F(object x)
  8.     {
  9.         Console.WriteLine("F(object)");
  10.     }
  11.     static void F(int x)
  12.     {
  13.         Console.WriteLine("F(int)");
  14.     }
  15.     static void F(double x)
  16.     {
  17.         Console.WriteLine("F(double)");
  18.     }
  19.     static void F<T>(T x)
  20.     {
  21.         Console.WriteLine("F<T>(T)");
  22.     }
  23.     static void F(double x, double y)
  24.     {
  25.         Console.WriteLine("F(double, double)");
  26.     }
  27.     static void Main()
  28.     {
  29.         F();                    // Invokes F()
  30.         F(1);                   // Invokes F(int)
  31.         F(1.0);                 // Invokes F(double)
  32.         F("abc");               // Invokes F(object)
  33.         F((double)1);           // Invokes F(double)
  34.         F((object)1);           // Invokes F(object)
  35.         F<int>(1);              // Invokes F<T>(T)
  36.         F(1, 1);                // Invokes F(double, double)
  37.     }
  38. }


As shown by the example, a particular method can always be selected by explicitly casting the arguments to the exact parameter types and/or explicitly supplying type arguments.

Post a Comment