params is not expanded unless necessary.
suggest changeThe following program:
class Program
{
static void Method(params Object[] objects)
{
System.Console.WriteLine(objects.Length);
}
static void Method(Object a, Object b)
{
System.Console.WriteLine("two");
}
static void Main(string[] args)
{
object[] objectArray = new object[5];
Method(objectArray);
Method(objectArray, objectArray);
Method(objectArray, objectArray, objectArray);
}
}
will print:
5
two
3
The call Method(objectArray) could be read in two ways: as one Object argument that happens to be an array (the params method would then report length 1), or as the params array itself. The non-expanded form takes precedence, so the program prints 5.
In the second expression, Method(objectArray, objectArray), both the expanded form of the first method and the traditional second method are applicable. In this case also, non-expanded forms take precedence, so the program prints two.
In the third expression, Method(objectArray, objectArray, objectArray), the only option is to use the expanded form of the first method, and so the program prints 3.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents