Leo Zhang
Leo Zhang

Reputation: 55

NullReferenceException for button array

class Puzzle
      {
        private int PUZZLESIZE = 3;
        private int col, row;
        private Button[,] buttons;

        public Puzzle()
        { 
        }

        public Puzzle(Form1 form1)
        {
            buttons = new Button[3, 3] 
            { { form1.button1, form1.button2, form1.button3 }, 
            { form1.button4, form1.button5, form1.button6 }, 
            { form1.button7, form1.button8, form1.button9 } };          
        }

        public void reset()
        {
            for (int i = 0; i < 3; i++)
                for (int j = 0; j < 3; j++)
                {
                    buttons[i, j].BackColor = Color.Lime;
                }
        }

buttons[i, j].BackColor = Color.Lime;

this line causes NullReferenceException when I call the reset method in Form1.cs. Any advice is appreciated!!!

Upvotes: 2

Views: 173

Answers (2)

Sean
Sean

Reputation: 62532

Are you sure you're calling the default constructor? It looks like your class requires a Form1 instance to function, so try removing the default constructor. If it fails to build you've got your answer!

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502835

Two problems:

  • It's possible that form1.button1 (etc) are null. You should validate this in the constructor.
  • If you call the parameterless constructor instead of the Puzzle(Form1) constructor, buttons will still be null. I suggest you get rid of the parameterless constructor.

I'd also advise that you use braces for all loops, i.e.

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        buttons[i, j].BackColor = Color.Lime;
    }
}

Yes, it takes more space - but it's clearer and less error-prone in my experience.

Upvotes: 3

Related Questions