3

I got a two dimensional Array

BoardTile tiles[,];

and then in Init(Point size) I set its size:

tiles = new BoardTile[size.X, size.Y];

And how do I initialize all those elements because it does not use default BoardTile() constructor. It just assigns null.

foreach(BoardTile t in tiles) t = new BoardTile()

Does not work. And when I try to call

foreach(BoardTile t in tiles) t.anything()

I get NullReferenceException.

2
  • Use a for loop for each dimension. That's shown in all array tutorials. foreach is introduced for enumerating collections Commented Mar 13, 2019 at 11:23
  • Also that's not a dynamically sized array, the array size will not change after initialization. Commented Mar 13, 2019 at 11:28

1 Answer 1

5

You can try nested loops:

  for (int i = 0; i < titles.GetLength(0); ++i)
    for (int j = 0; j < titles.GetLength(1); ++j)
      titles[i, j] = new BoardTile();

Edit: if nested loops are too complex and unreadable, try switching to jagged arrays i.e. array of array - BoardTile tiles[][]; - from 2D one BoardTile tiles[,], e.g.

   // created and initialized jagged array
   BoardTile tiles[][] = Enumerable
     .Range(size.Y)                      // size.Y lines
     .Select(y => Enumerable             // each line is
        .Range(size.X)                   //   size.X items
        .Select(x => new BoardTile())    //   each of them is BoardTile()
        .ToArray())                      //   materialized as array
     .ToArray();                         // all arrays are array of array 
Sign up to request clarification or add additional context in comments.

3 Comments

Is it the only way? I thought about this solution, but this looks for me like it could be done easier.
@SkillGG: unlike jagged arrays (array of array BoardTile[][]) multidimensional ones (BoardTile[,]) are not very handy.
Okay. Thank for your help. I guess I'm stuck with this ugly double-loop init.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.