2

the Question may be very basic, but I stumbeled across a line of Code I have never seen and was wondering what the use of the Square Brackets are.

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

1.  private NodeItem[,] map;

2.  map = new NodeItem[width, height];

Can someone explain to me how 1 and 2 work and what the advantage of this might be?

  • [Multidimensional Arrays](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays) – Steve Aug 19 '18 at 10:27
  • https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/multidimensional-arrays – Rutger Vk Aug 19 '18 at 10:28
  • So basically with the NodeItem[,] you are creating an 2d array of NodeItems (not yet initialized). so you create an arrays within a array filled with NodeItems – Rutger Vk Aug 19 '18 at 10:30

2 Answers2

3

This is'nt 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 initializing the array, with a new statement (new <Type>[<itemsNumber>])). An array is a set of objects, which any object should be initialized - any array element (the term to an item of the 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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
3

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)

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121