Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple "params" parameters possible?

Is it possible to have multiple params parameters in C#? Something like this:

void foobar(params int[] foo, params string[] bar) 

But I'm not sure if that's possible. If it is, how would the compiler decide where to split the arguments?

like image 682
garytchao Avatar asked Aug 07 '12 03:08

garytchao


People also ask

What is params params?

Params is an important keyword in C#. It is used as a parameter which can take the variable number of arguments. Important Point About Params Keyword : It is useful when programmer don't have any prior knowledge about the number of parameters to be used.

When should I use params?

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.


Video Answer


2 Answers

You can only have one params argument. You can have two array arguments and the caller can use array initializers to call your method, but there can only be one params argument.

void foobar(int[] foo, string[] bar)  ...  foobar(new[] { 1, 2, 3 }, new[] { "a", "b", "c" }); 
like image 155
Samuel Neff Avatar answered Oct 11 '22 15:10

Samuel Neff


No this is not possible. Take this:

void Mult(params int[] arg1, params long[] arg2) 

how is the compiler supposed to interpret this:

Mult(1, 2, 3); 

It could be read as any of these:

Mult(new int[] {         }, new long[] { 1, 2, 3 }); Mult(new int[] { 1       }, new long[] {    2, 3 }); Mult(new int[] { 1, 2    }, new long[] {       3 }); Mult(new int[] { 1, 2, 3 }, new long[] {         }); 

You can take two arrays as params like this however:

void Mult(int[] arg1, params long[] arg2) 
like image 41
Cole Tobin Avatar answered Oct 11 '22 15:10

Cole Tobin