Wednesday, August 07, 2013

The mysterious ways of the params keyword in C#

If a parameter to a C# method is declared with the params keyword, then it can match either itself or a comma-separated list of um itselves(?). Consider:

class Program {
  static void Sample(params int[] ints) {
   for (int i = 0; i < ints.Length; i++) {
    System.Console.WriteLine("{0}: {1}", i, ints[i]);
  public static void Main() {
   Sample(new int[] { 1, 2, 3 });
   Sample(9, 10);
This program prints

0: 1
1: 2
2: 3
0: 9
1: 10
The first call to Sample does not take advantage of the params keyword and passes the array explicitly (formally known as normal form). The second call, however, specifies the integers directly as if they were separate parameters. The compiler generates a call to the function in what the language specification calls expanded form.

Normally, there is no conflict between these two styles of calling a function with a params parameter because only one form actually makes sense.

Sample(new int[] { 0 }); // normal form
Sample(0); // expanded form
The first case must be called in normal form because you cannot convert an int[] to an int; conversely, the second case must be called in expanded form because you cannot convert an int to an int[].

Read more: The Old New Thing
QR: Inline image 1