A parameter declared with a params
modifier is a params parameter. A params parameter must be the last parameter in the formal parameter list, and the type of a params parameter must be a single-dimension array type. For example, the types int[]
and int[][]
can be used as the type of a params parameter, but the type int[,]
cannot be used in this way.
A params parameter enables a caller to supply values in one of two ways.
A method is permitted to assign new values to a params parameter. Such assignments only affect the local storage location represented by the params parameter.
The example
void F(params int[] values) { Console.WriteLine("values contains %0 items", values.Length); foreach (int value in values) Console.WriteLine("\t%0", value); } void G() { int i = 1, j = 2, k = 3; F(new int[] {i, j, k); F(i, j, k); }
shows a method F
with a params parameter of type int[]
. In the method G
, two invocations of F
are shown. In the first invocation, F
is called with a single argument of type int[]
. In the second invocation, F
is called with three expressions of type int
. The output of each call is the same:
values contains 3 items: 1 2 3
A params parameter can be passed along to another params parameter. In the example
void F(params object[] fparam) { Console.WriteLine(fparam.Length); } void G(params object[] gparam) { Console.WriteLine(gparam.Length); F(gparam); } void H() { G(1, 2, 3); }
the method G
has a params parameter of type object[]
. When this parameter is used as an actual argument for the method F
, it is passed along without modification. The output is:
3 3
The example
void F(params object[] fparam) { Console.WriteLine(fparam.Length); } void G(params object[] gparam) { Console.WriteLine(gparam.Length); F((object) gparam); // Note: cast to (object) } void H() { G(1, 2, 3); }
shows that it is also possible to pass the params parameter as a single value by adding a cast. The output is: