C #: method signatures?

Let's say I create these two methods:

public void AddScriptToPage(params string[] scripts) { /*...*/ }
public void AddScriptToPage(string href, string elementId) { /*...*/ }

Which of these methods gets called below and why?

AddScriptToPage("dork.js", "foobar.js");

How does the compiler determine which method to call?

+5
source share
2 answers

The second method is called if an exact match is found, it is used before the parameters.

From MSDN :

When overload resolution is performed, a method with an array of parameters can be applied either in its normal form or in an expanded form (section 7.4.2.1). The extended form of the method is available only if the normal form of the method is not applicable and only if the method with the same signature as the extended form is not yet declared in the same type.

Example:

using System;
class Test
{
   static void F(params object[] a) {
      Console.WriteLine("F(object[])");
   }
   static void F() {
      Console.WriteLine("F()");
   }
   static void F(object a0, object a1) {
      Console.WriteLine("F(object,object)");
   }
   static void Main() {
      F();
      F(1);
      F(1, 2);
      F(1, 2, 3);
      F(1, 2, 3, 4);
   }
}

Output:

F();
F(object[]);
F(object,object);
F(object[]);
F(object[]);
+8
public void AddScriptToPage(string href, string elementId) 

.. . , .

+5

All Articles