5

Let's say I create these two methods:

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

Which one of these methods gets call by the code below, and why?

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

How does the compiler determine which method to call?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
JamesBrownIsDead
  • 4,655
  • 6
  • 30
  • 29

2 Answers2

8

Your second method gets called, if an exact match is found, it's used before params.

From MSDN:

When performing overload resolution, a method with a parameter array may be applicable either in its normal form or in its expanded form (Section 7.4.2.1). The expanded form of a method is available only if the normal form of the method is not applicable and only if a method with the same signature as the expanded form is not already declared in the same type.

Their 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[]);
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • This is particularly confusing to people when they call F(null). Do you get F((object[])null) or F(new object[] { null } ) ? Many people expect the latter, but since the former is applicable in the normal form, it is better. – Eric Lippert Jan 30 '10 at 18:41
  • @Eric - You never cease to amaze me with a deep framework question/fact I'd never think of...but end up using in practice months later. Some of your answers here have made tremendous performance differences for me, keep it up. – Nick Craver Jan 30 '10 at 19:04
  • Along the lines of your comment, if you haven't read the annotated specification published by Microsoft, you really should; it's a gold mine. – jason Jan 30 '10 at 22:37
5
public void AddScriptToPage(string href, string elementId) 

.. will get called. The compiler chooses the signature with the most accurate match, with params having least priority.

cwap
  • 11,087
  • 8
  • 47
  • 61