2

Hopefully this is not a duplicate as I did do a search and found nothing.

At first glance I thought they would behave similarly but no. One is a 2 dimensional array of string and the other is an array of string arrays, i.e. what you get back from (List<string[]>)obj.ToArray().

I know how to return the jagged array type using (List<string[]>)obj.ToArray().

How can I return 2d array using a similar concept, i.e. build up a collection object from other data and call ToArray or other method that will return a 2d array.

Thanks

8
  • What is the difference between a 2d array of strings and an array of string arrays? I don't see one... at least not in utility. Commented Jun 27, 2013 at 18:27
  • Arrays (C# Programming Guide) Commented Jun 27, 2013 at 18:27
  • @evanmcdonnal new[] { new string[1], new string[2] }, that's possible with string[][] but not with string[,]. Commented Jun 27, 2013 at 18:27
  • classic case of diplopia Commented Jun 27, 2013 at 18:28
  • @hvd Ah, I see the difference now. I would never do that though... and I'd probably call you an idiot if you did :-&( Commented Jun 27, 2013 at 18:29

2 Answers 2

8

One is a jagged array, where the other is a multidimensional array.

There are some differences. A multidimensional array will guarantee each row having the length. With a jagged array, each "row" is an array, and those arrays can be varying sizes.

Another difference is in memory layout. A multidimensional array is a single object, the array elements are guaranteed to be closer together in memory. Since a jagged array, is an array of arrays, there is no guarantee that the each array will be allocated sequentially in memory, particularly in multi-threaded situations.

It is also good to note that the .NET Framework Design Guidelines for Array Usage suggests to use jagged arrays over multidimensional:

√ CONSIDER using jagged arrays instead of multidimensional arrays.

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

2 Comments

Cool. A downvote without an explanation why.
If you want your rows allocated sequentially in memory (ie, you are working with bitmaps / video buffer) then you will want a multidimensional array rather than a jagged array.
1

jagged array is string[][] 2d array is string[,]

In other words with string[,] each row has the same number of elements. in string[][] each row may have a different number of elements.

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.