1

What is the difference between these two:

string[,] array1;

and

string[][] array2;

Could someone please explain me about these two in terms of applications and functionality, memory management etc... how do you called them, which one is better to use? how to initialize them?

  • 2
    "better" depends on "for what purpose"; a rectangular array is good for rectangular data; a jagged array is good for jagged data – Marc Gravell Mar 28 '20 at 15:12
  • Also note that jagged array have much better speed against multi dimension specially when dealing with large data, like 100x100 or more – epsi1on Mar 28 '20 at 15:20

1 Answers1

2

array1 is called a reference to a multidimensional array; array2 is a reference to a jagged array.

The first one is designed to store rectangular data which is not sparse and the number of elements in the dimensions are almost the same. You can initialize it like:

// Two-dimensional array.
int[,] array1= new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

In the latter case which is also called array of array the elements can be of different dimensions and sizes. Some times it is memory optimized to store sparse 2d data in the RAM. You can initialize it like:

int[][] array2= new int[][] 
{
    new int[] { 1, 3, 5, 7, 9 },
    new int[] { 0, 2, 4, 6 },
    new int[] { 11, 22 }
};

Absolutely the usage is depends on you requirements and purposes. You can review these 1, 2.

Alireza Mahmoudi
  • 964
  • 8
  • 35
  • Could you please explain me about these two in terms of applications and functionality, memory management etc... how do you called them, which one is better to use? – Bita tehrani Mar 28 '20 at 15:13
  • I personally always use array of arrays `int[][] ` – Ashkan Mobayen Khiabani Mar 28 '20 at 15:43
  • @Bitatehrani: This isn't a tutorial site; if you have a lot of questions about how to use a language feature effectively, you might want to consult a good book or take a class. The one that is *better* to use is the one that solves your problem better; rectangular arrays are best *when the shape of the data is rectangular* and jagged arrays are best *when the shape of the data is jagged*. There is no "better" without a job; if I asked you whether a hammer or a screwdriver was the better tool but not what job I was trying to do, how would you answer? – Eric Lippert Mar 28 '20 at 15:58