164
LESSON 13 Understanding scope
// A field.
int a = 1;
private void clickMeButton_Click(object sender, EventArgs e)
{
// A method variable.
int b = 2;
MessageBox.Show(“a = “ + a.ToString() +
“\nb = “ + b.ToString());
}
private void clickMeTooButton_Click(object sender, EventArgs e)
{
// A method variable.
int c = 3;
MessageBox.Show(“a = “ + a.ToString() +
“\nc = “ + c.ToString());
}
}
}
The field a is declared outside of the three methods (Form1, clickMeButton_Click, and
clickMeTooButton_Click) so it has class scope. That means the code in any of the methods can
see and use this variable. In this example, the two
Click event handlers each display the value.
The variable
b is declared within clickMeButton_Click so it has method scope. Only the code
within this method that comes after the declaration can use this variable. In particular, the code in
the other methods cannot see it.
Similarly, the code in the
clickMeTooButton_Click event handler that comes after the c declaration
can see that variable.
Two variables with the same name cannot have the same scope. For example, you cannot create two
variables named
a at the class level nor can you create two variables named b inside the same method.
Same Named Variables
Although you cannot give two variables the same name within the same scope, you can give them
the same name if they are in different methods or one is a field and the other is declared inside a
method. For example, the following code defines three variables all named
count:
// A field.
int count = 0;
private void clickMeButton_Click(object sender, EventArgs e)
{
// A method variable.
int count = 1;
MessageBox.Show(count.ToString());
}
596906c13.indd 164 4/7/10 12:32:47 PM