Sunday, August 22, 2010

#1 Params

A simple question. What would be printed out after execution?

void Main()
{
 Foo();
 Foo(null)
 Foo(null as object)
}

void Foo(params object[] args)
{
 if (args == null)
  Console.WriteLine("Null");
 else
  Console.WriteLine(args.Length);
}


* This source code was highlighted with Source Code Highlighter.

The answer is:
0
Null
1

Pretty straightforward, but good enough for an interview.

UPD: Some explanation for this. According to C# specification:
A parameter array permits arguments to be specified in one of two ways in a method invocation:
  • The argument given for a parameter array can be a single expression of a type that is implicitly convertible to the parameter array type. In this case, the parameter array acts precisely like a value parameter.
  • Alternatively, the invocation can specify zero or more arguments for the parameter array, where each argument is an expression of a type that is implicitly convertible to the element type of the parameter array. In this case, the invocation creates an instance of the parameter array type with a length corresponding to the number of arguments, initializes the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument.
So parsing of Foo() goes by second point and Foo() is actually called as Foo(new[0]{}).
Next, Foo(null) goes by first point - as far as null literal is implicitly convertible to object[]. So, Foo(null) is called as Foo(null).
And last, Foo(null as object) goes be second point, as far as null as object is not a null literal and should be treated as reference (though, null reference). According to this, Foo(null as object) is called as Foo(new object[1]{null as object}).

No comments:

Post a Comment