The params
parameter modifer gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params
parameter:
1) Calling with an array of the parameter type, in which case the params
keyword has no effect and the array is passed directly to the method:
object[] array = new[] { "1", "2" };
// Foo receives the 'array' argument directly.
Foo( array );
2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:
// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );
// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );
In order to pass in an object array to a method with a "params object[]
" parameter, you can either:
1) Create a wrapper array manually and pass that directly to the method, as mentioned by lassevk:
Foo( new object[] { array } ); // Equivalent to calling convention 1.
2) Or, cast the argument to object
, as mentioned by Adam, in which case the compiler will create the wrapper array for you:
Foo( (object)array ); // Equivalent to calling convention 2.
However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "params object[][]
" parameter. This would allow you to pass multiple arrays as arguments:
void Foo( params object[][] arrays ) {
foreach( object[] array in arrays ) {
// process array
}
}
...
Foo( new[] { "1", "2" }, new[] { "3", "4" } );
// Equivalent to:
object[][] arrays = new[] {
new[] { "1", "2" },
new[] { "3", "4" }
};
Foo( arrays );