1

I have no idea why this isn't working

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }
    private Button[,] button = new Button[3, 3]{ {button1, button2, button3 },
                                                 {button4, button5, button6 },
                                                 {button7, button8, button9 } };
    private void button_Click(object sender, EventArgs e)
    {

    }
}

I get the error

a field initializer cannot reference the nonstatic field

on all 9 Buttons

Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Khaled Yasser
  • 11
  • 1
  • 2
  • These buttons have to be referenced from static fields. This is what the compiler is telling you. If you don't like this, initialize `button` from the constructor. – Yacoub Massad May 28 '16 at 13:33
  • See this for an explanation why: http://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property – Yacoub Massad May 28 '16 at 13:34

1 Answers1

3

A field initializer (as the error clearly states) can not reference nonstatic fields or values. button1 to button9 are not static. To achieve the same result, move your array initialization in the constructor of your form:

private Button[,] button;

public Form1()
{
    InitializeComponent();

    button = new Button[3, 3]{ {button1, button2, button3 },
                                {button4, button5, button6 },
                                {button7, button8, button9 } };
}
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62