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?

2
  • The first one is "jagged" - an array of references to arrays. Commented Feb 7, 2016 at 10:13
  • 6
    Have a look at this answer. Commented Feb 7, 2016 at 10:14

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Also check Arrays
"an array of pointers to arrays" - that depends on how its used- the elements might be unitialised. 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"
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).

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.