3

The syntax is slightly different but what is the difference between them.

public static string[][] str1 = { new string[] { Total, "N2" }};
public static string[,] str2 = { { Total, "N2" } }; 

What are the guidelines for the use of each?

ehh
  • 3,412
  • 7
  • 43
  • 91

3 Answers3

6

Have a look here: https://msdn.microsoft.com/en-us/library/2s05feca.aspx

Basically, the difference is how the memory is allocated. [,] notation will allocate all of the needed memory in one block, while [][] notation will allocate an array of pointers to arrays, where each array is allocated separately and not necessarily next to the others

Bar Mako
  • 133
  • 1
  • 7
  • Also check [Arrays](https://msdn.microsoft.com/en-us/library/k2604h5s.aspx) – shadow Feb 07 '16 at 10:22
  • 3
    _"an array of **pointers** to arrays"_ - that depends on how its used- the elements might be [unitialised](https://msdn.microsoft.com/en-us/library/2s05feca.aspx). Also, in c# the term "pointer" is not used commonly and should not be a synonym for _reference_. _"[A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null](https://msdn.microsoft.com/en-us/library/2s05feca.aspx)"_ –  Feb 07 '16 at 10:25
0

In the examples you quoted:

public static string[][] str1 = { new string[] { Total, "N2" }};
public static string[,] str2 = { { Total, "N2" } };

The first one is an array of arrays (Jagged Array). Each entry can point to an array of string.

The second one is a normal 2 dimensional array (Multi Dimensional Array).

Habeeb
  • 7,601
  • 1
  • 30
  • 33
0

In a nutshell , [,] is a 2d array allocated all at once, while [][] is an array of arrays thus memory allocation is gradual- the initialization syntax (as you pointed out) is different also.

One more important difference is that in a [][] type you can define each 'row' of a different size. which you can't do in [,] which is in a way a C# representation of a Matrix.

Ilan Kutsman
  • 469
  • 3
  • 9