Khaled Yasser
Khaled Yasser

Reputation: 11

a field initializer cannot reference the nonstatic field

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

Upvotes: 1

Views: 2991

Answers (1)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

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 } };
}

Upvotes: 3

Related Questions