What is the use of square brackets ([]) when constructing an object in C#

3k Views Asked by At

I stumbled across a line of code I have never seen. Given this code:

public NodeItem (bool isWall, Vector2 pos, int x, int y)
{
    this.isWall = isWall;
    this.pos = pos;
    this.x = x;
    this.y = y;
}

What is the purpose/use of the square brackets in this code?

private NodeItem[,] map;

map = new NodeItem[width, height];
2

There are 2 best solutions below

1
On BEST ANSWER

This isn't an object. When you're using square brackets, you're declaring an array (unlike C and C++, you don't specify the numbers of elements. Instead, you do this when you initialize the array with a new statement, such as new <Type>[<itemsNumber>]).

An array is a set of objects (which any object should be initialized) - any array element (the term for a single item of a given array) contains the object's default value - 0 for numbers, null for reference types and pointers, etc.

But when you're declaring an array, you save you a place in the memory to store the array elements (arrays are reference types, so they are stored in the heap).

When you're using a comma inside an array declaration, you're declaring a multidimensional array. This is a matrix (for 2D array; it may be 3D, 4D, etc.). To access an array element, you specify in the square brackets all the indexes, separated by commas.

For more details about arrays in C# see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/, and about multidimensional arrays - see https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays.

0
On

In c#, x[] is an array of type x. x[,] is a two-dimensional array (and naturally, x[,,] is a three-dimensional array and so on).

So - private NodeItem[,] map; is declaring a field that is a two-dimensional array of NodeItem, named map.

The line after that - map = new NodeItem[width, height]; initialize the array - so it now contains width * height references to NodeItem, all implicitly initialized to default(NodeItem) - null for reference types, and whatever default value for value types.

For further reading, Arrays (C# Programming Guide) And Multidimensional Arrays (C# Programming Guide)