Array/Matrix Definition with [][] or [,]

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,


I´m new in programming with C# and having some troubles with
understanding the definitions of multi-dimensional arrays.

Is there any difference between defining an Array with [][] or [,]?


I tried to define it like this:

int[][] test = new int[list1.Count][list2.Count]

but this doesn´t work.


A definition like:

int[,] test = new int[list1.Count, list2.Count]


seems to work.


So I am asking myself now what is right and if there are any differences.

Or do I have a mistake in my first try to define an 2-dimensional array?



Regards,

Martin
 
Hi Martin,

A multidimensional array is in C# defined with a , per dimension, so your
second definition is correct.

int[,] test = new int[list1.Count, list2.Count]


Hello,


I´m new in programming with C# and having some troubles with
understanding the definitions of multi-dimensional arrays.

Is there any difference between defining an Array with [][] or [,]?


I tried to define it like this:

int[][] test = new int[list1.Count][list2.Count]

but this doesn´t work.


A definition like:

int[,] test = new int[list1.Count, list2.Count]


seems to work.


So I am asking myself now what is right and if there are any differences.

Or do I have a mistake in my first try to define an 2-dimensional array?



Regards,

Martin
 
If you want a square m-by-n array, then the [,] and [m,n] syntax is correct
and more convenient; [][] declares a /jagged/ array - i.e. an array of
arrays (which is useful if you don't need each row to have the same width),
but means that you mean to manually assign each row (to determine the
length) - for instance:

int[][] data = new int[3][]; // 3 rows
data[0] = new int[7]; // first row is 7 wide
data[1] = new int[9];
data[2] = new int[4];

Marc
 
Back
Top