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

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
 
M

Morten Wennevik

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
 
M

Marc Gravell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top