int[] data1 = new int [] { 1, 2, 3 };
can be simplified as
int[] data2 = new [] { 1, 2, 3 };
int[][] table1 = new int[][] { new int[] { }, new int[] { 1, 2 } };
cannot be simplified as
int[][] table2 = new [][] { new int[] { }, new int[] { 1, 2 } };
For the second case, why cannot we just use [][]
instead of int[][]
?
An int[][]
is an array of arrays. If you are explicitly typing it as int[][]
then it works (as you can see) but if you are using implicit typing then the code works it out differently.
the syntax new []
says "I'm creating an array but I want you to work out the type. Consider the following working example:
new [] { new int [] { }, new [] { 1, 42 } }
Here we say we want a new implicitly typed array. The compiler then looks at our initialiser to work out the type of that array. In this case it sees two items: the first is an explicitly typed empty array of type int[]
, the second is an implicitly typed array. When the compiler examines the second item's contents it discovers it is an int[]
as well so determines that the overall expression defines an int[][]
.
In the above example we need to explicitly type the first empty array because otherwise the compiler would have no idea of its type since it has no items to use to determine the type.
Thanks to William Andrew Montgomery for providing me the first hint to get to this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With