Robbebeest Robbebeest - 1 month ago 21
C# Question

How to add 2D arrays to a list in C#?

I want to make a list of 2D (boolean) arrays. I have declared the empty list block itself and made an empty 2D boolean array called blockStructure. Also I made a method blocks where I give blockStructure a different value and then add it to the to the block list.

class TetrisBlock
{
public List<bool[,]> block;
public bool[,] blockStructure;
}

public Tetrisblock(Texture2D sprite)
{
blockTexture = sprite;
blockStructure = new bool[2, 2];
}

List<bool[,]> blocks()
{
blockStructure = new bool[,] // first 2D array
{
{ false, true},
{ false, false}
};
block.Add(blockStructure);

blockStructure = new bool[,] // second 2D array
{
{ true, true},
{ false, false}
};
block.Add(blockStructure);

return block;
}

public void draw (GameTime gameTime, SpriteBatch spriteBatch)
{
for (int x = 0; x < 2; x++)
{
for (int y = 0; y < 2; y++)
{
if (blok[1][x,y])
{
spriteBatch.Draw(sprite, new Vector2(blockTexture.Width*x, blockTexture.Height*y, Color.White)
}
}
}
}


The error that I get says that list block has value null. For some reason the 2D arrays don't get added to the list. Does someone know a solution?

Answer

You must initialize the List<bool[,]> block list before you can add items to it. This line just defines the reference which at first refers to nothing, null, but you must have a block = new List<bool[,]>() for the list to be initialized