Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between string[,] and string[][] [duplicate]

Tags:

c#

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

like image 759
John Aschenbrenner Avatar asked Jun 30 '26 22:06

John Aschenbrenner


1 Answers

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.

like image 88
Christopher Currens Avatar answered Jul 02 '26 10:07

Christopher Currens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!