Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot we just use [][] instead of int[][]?

Tags:

arrays

c#

Case 1:

int[] data1 = new int [] { 1, 2, 3 };

can be simplified as

int[] data2 = new [] { 1, 2, 3 };

Case 2:

int[][] table1 = new int[][] { new int[] { },  new int[] { 1, 2 } };

cannot be simplified as

int[][] table2 = new [][] { new int[] { }, new int[] { 1, 2 } };

Question:

For the second case, why cannot we just use [][] instead of int[][]?

like image 640
kiss my armpit Avatar asked Jun 08 '14 18:06

kiss my armpit


1 Answers

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.

like image 195
Chris Avatar answered Oct 21 '22 19:10

Chris