Reputation: 191
For the following code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
public int x = 5;
MessageBox.Show(x.ToString());
}
}
I have the following error
Invalid expression term 'public'
on the line public int x = 5;
Why can't I define public objects inside event handler?
Upvotes: 0
Views: 1715
Reputation: 2226
public
is an access modifier for types (e.g. public class Foo
) and type members (such as methods, properties, or fields on a class, e.g. button3_Click
).
You are trying to declare a local variable inside a method as public, which is not allowed.
One way to fix the compilation error is to remove the access modifier from the local variable declaration in button3_Click
: int x = 5;
instead of public int x = 5;
. You should use this if you only need to access the variable x
within button3_Click
and you are happy to have a new variable instantiated for every time button3_Click
is called.
Another way to fix the compilation error is to change x
from a local variable to a field. By changing where x
is defined, you can declare it as a field on Form1
instead of a local variable in the button3_Click
scope.
Try:
public partial class Form1 : Form
{
public int x;
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
x = 5;
MessageBox.Show(x.ToString());
}
}
This option is preferable if you need to access the x
field from other methods in your program, or you want to preserve values across multiple invocations of the button3_Click
method on the Form1
instance.
If these are the case, you could also decide to make x
a property instead of a field in order to gain more fine-grained control over reading, writing, and/or computation of x
.
Upvotes: 2