Why can't the params parameter take multi-dimensional array as parameter C#

This question might be annoying. I would really love if you could help me.

So the below code is all fine:

public void jj(int g, params int[][] h) {

}

whilst, this is not fine:

public void jj(int g, params int[,] h) {

}

Can you please tell me why the params parameter take multi-dimensional array as parameter whilst It can, in case of jagged arrays?

>Solution :

The idea of params is that in the calling code you can write multiple separate arguments, each being of the argument type, and the compiler will create an array for you. So you could have:

public void SomeMethod(params int[] numbers) { ... }

SomeMethod(1, 2, 3);

The compiler would convert that call into something like:

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

For a single-dimensional array, that’s straightforward – but what would it do if you had that same method call with an int[,] parameter?

In your "array of arrays" example, it’s still easy enough – because each argument would still need to be an int array, for example, in this code:

public void SomeMethod(params int[] numbers) { ... }

int[] x1 = { 1, 2, 3 };
int[] x2 = { 4, 5, 6 };
SomeMethod2(x1, x2);

… the method call is equivalent to SomeMethod2(new int[][] { x1, x2 });.

But you can’t create an int[,] directly from multiple single-dimensional arrays. (You can create the rectangular array and then copy the contents of the single-dimensional arrays, but that’s not the same thing at all.)

Leave a Reply