0

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?

  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Gilad Green Oct 12 '16 at 18:05

2 Answers2

2

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

Gilad Green
  • 34,248
  • 6
  • 46
  • 76
1

You never gave block a value:

block = new List<bool[,]>();

Any reference type is null by default until you instantiate it to something.

David
  • 176,566
  • 33
  • 178
  • 245