A
Alan Foxmore
Hi everyone,
I'm new to C# and I was hoping I could get some clarification on the
syntax for jagged and multidimensional arrays.
Here is my question:
The following syntax is correct for declaring a multi-dimensional
array:
int[,] v = {{ 3, 6, 4 },
{ 2, 8, 1 }};
If I declare a similar jagged array, however, I have to do this
instead:
int[][] w = {new int[] { 3, 6, 4 },
new int[] { 2, 8, 1 }};
Specifically, the "new int[]" declarations are absolutely necessary to
avoid a compiler error. If you remove the "new int[]" from the
declaration you get this compiler error:
"Array initializers can only be used in a variable or
field initializer. Try using a new expression instead."
I know that v is a multi-dimensional array and w is an "array of int
array". So I understand the difference in semantics. But I can't
articulate *why* there is a difference in the syntax.
Thanks very much.
I'm new to C# and I was hoping I could get some clarification on the
syntax for jagged and multidimensional arrays.
Here is my question:
The following syntax is correct for declaring a multi-dimensional
array:
int[,] v = {{ 3, 6, 4 },
{ 2, 8, 1 }};
If I declare a similar jagged array, however, I have to do this
instead:
int[][] w = {new int[] { 3, 6, 4 },
new int[] { 2, 8, 1 }};
Specifically, the "new int[]" declarations are absolutely necessary to
avoid a compiler error. If you remove the "new int[]" from the
declaration you get this compiler error:
"Array initializers can only be used in a variable or
field initializer. Try using a new expression instead."
I know that v is a multi-dimensional array and w is an "array of int
array". So I understand the difference in semantics. But I can't
articulate *why* there is a difference in the syntax.
Thanks very much.