0

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?

1
  • 2
    How would the compiler infer how many dimensions your array has, when you can only provide a comma separated list? Commented Jul 26, 2022 at 21:39

3 Answers 3

4

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.)

Sign up to request clarification or add additional context in comments.

Comments

2

Short answer? Because that's how the spec is defined: https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0225

Long answer: https://stackoverflow.com/questions/37610411/using-params-keyword-with-a-multidimensional-array#:~:text=params%20isn't%20about%20passing,be%20a%20one%20dimensional%20array.

params isn't about passing multi dimensional data, it's about passing a variable number of arguments to a function. Since that list of arguments is inherently one dimensional that's why the type has to be a one dimensional array.

1 Comment

To be honest, I would love the long answer)
1

For the first example, the parameter type is int[], an array of integers.

What would you expect as parameter type for the second example?`

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.