Tom
Tom

Reputation: 540

What does it mean, in 2D Array, to initialize with first dimension size zero?

I have seen 2D arrays being initialized as:

// Two-dimensional array with no boundary on dimension.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with implicit dimensions sizes.
int[,] array2Db = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

// Ref: https://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx

But what does it mean to initialize with one of the dimensions as zero? For example, I recently came across something like:

int[,] array2Dzero = new int[0,4];

Does this mean that the first dimension can be of any size? If yes, is there a documentation of this anywhere?

Upvotes: 0

Views: 125

Answers (3)

Sean
Sean

Reputation: 296

int[,] array2Dzero = new int[0,4];

It literally make the first dimension of zero size. So it has 0 * 4 elements, or simply 0 elements. So initializing it this way means that it is intended to have the first dimension changed later in the code to another permanent state or the array is simply not used. However, a jagged array or simply waiting till later in the program to 'new' the array is probably still a better solution.

Upvotes: 1

matt-dot-net
matt-dot-net

Reputation: 4244

It means the entire array is of zero length. An array's length in memory is the product of all dimension lengths. You can verify with:

Console.WriteLine(array2Dzero.Length);

The output of this will be "0"

Upvotes: 2

Jamiec
Jamiec

Reputation: 136074

Does this mean that the first dimension can be of any size?

No, it means the first dimension has a size of zero.

See: http://rextester.com/NYPLJ69377

What does this mean? It means the array is nigh on unusable until you've expanded that dimension.

array2Dzero[0,0] = 123; // IndexOutOfRangeException

Upvotes: 2

Related Questions