Search code examples
c#object-initialization

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


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];

Solution

  • 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.