-2

I recently discovered that two ways to declare array in C#, those are:

  • int[,] array = new int[4, 2];
  • int[] test = { 4, 2 };

Could anyone please describe the difference between those two statements?

Timothy G.
  • 6,335
  • 7
  • 30
  • 46
Sithum
  • 7
  • 7
  • 1
    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/ – Roman Ryzhiy Dec 13 '22 at 17:17
  • 2
    Does this answer your question? [What are the differences between a multidimensional array and an array of arrays in C#?](https://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays), though I'm going to assume you know what `int[]` is and you really want to know about `int[][]`. – gunr2171 Dec 13 '22 at 17:20
  • `int[,] array = new int[4, 2];` - 2d array `4x2`. `int[] test = { 4, 2 };` 1d array with 2 items which are `2` and `4` – Dmitry Bychenko Dec 13 '22 at 17:23
  • `int[,]` is 2-dimensional. It is a matrix having rows and columns. Elements must be accessed through 2 indexes: `int element = array[x, y];`. `int[]` has one dimension and one index is required: `int element = text[i];`. An array can have up to 32 dimensions (32 indexes). – Olivier Jacot-Descombes Dec 13 '22 at 17:24
  • @gunr2171 OP never mentioned jagged arrays (`int[][]`), they have a multidimensional array and a basic array with implicit initialization. – Magnetron Dec 13 '22 at 17:26
  • I'd argue that `int[]` is a multidimensional array with a dimension of 1, and `int[][]` is a dimension of 2. – gunr2171 Dec 13 '22 at 17:41
  • here's another way to declare an array that makes things really confusing, `Array.CreateInstance(typeof(object), new[] { 0, byte.MaxValue, short.MaxValue, int.MaxValue }, new[] { int.MinValue, short.MinValue, byte.MinValue, 0 });` – Jodrell Dec 14 '22 at 07:47

1 Answers1

3
int[,] array = new int[4, 2]; 

creates array with 8 elements having the default value of 0 and 2 dimensions

int[] test = { 4, 2 }; 

creates array with 2 elements(4 and 2) and 1 dimension

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188