Understanding Scope
A variable’s scope is the code that can “see” or access that variable. It determines whether a
piece of code can read the variable’s value and give it a new value.
In this lesson you learn what scope is. You learn why restricting scope is a good thing and how
to determine a variable’s scope.
SCOPE WITHIN A CLASS
A C# class (and note that Form types are classes, too) contains three main kinds of scope:
class scope, method scope, and block scope. (If you have trouble remembering what a class
is, review Lesson 9’s section “Understanding Classes and Instances.”)
Variables with class scope are declared inside the class but outside of any of its methods.
These variables are visible to all of the code throughout the instance of the class and are
known as fields.
Variables with method scope are declared within a method. They are usable by all of the code
that follows the declaration within that method.
Variables with block scope are declared inside a block defined by curly braces {} nested inside
a method. The section “Block Scope” later in this lesson says more about this.
For example, consider the following code that defines the form’s constructor (
Form1), a field,
and some variables inside event handlers:
namespace VariableScope
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
13
596906c13.indd 163 4/7/10 12:32:47 PM
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() +
“ b = “ + b.ToString());
}
private void clickMeTooButton_Click(object sender, EventArgs e)
{
// A method variable.
int c = 3;
MessageBox.Show(“a = “ + a.ToString() +
“ c = “ + 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
Scope Within a Class
165
private void clickMeTooButton_Click(object sender, EventArgs e)
{
// A method variable.
int count = 2;
MessageBox.Show(count.ToString());
}
In this example, the method-level variable hides the class-level variable with the same name. For
example, within the
clickMeButton_Click event handler, its local version of count is visible and
has the value
1. The class-level field with value 0 is hidden.
You can still get the class-level value if you prefix the variable with the executing
object. Recall that the special keyword
this means “the object that is currently
executing this code.” That means you could access the class-level field while
inside the
clickMeButton_Click event handler like this:
private void clickMeButton_Click(object sender, EventArgs e)
{
// A method variable.
int count = 1;
MessageBox.Show(count.ToString());
MessageBox.Show(this.count.ToString());
}
Usually it’s better to avoid potential confusion by giving the variables different
names in the first place.
Method Variable Lifetime
A variable with method scope is created when its method is executed. Each time the method is called,
a new version of the variable is created. When the method exits, the variable is destroyed. If its value
is referenced by some other variable, it might still exist, but this variable is no longer available to
manipulate it.
One consequence of this is that the variable’s value resets each time the method executes. For example,
consider the following code:
private void clickMeButton_Click(object sender, EventArgs e)
{
// A method variable.
int count = 0;
count++;
MessageBox.Show(count.ToString());
}
Each time this code executes, it creates a variable named count, adds 1 to it, and displays its value.
The intent may be to have the message box display an incrementing counter but the result is actually
the value
1 each time the user clicks the button.
596906c13.indd 165 4/7/10 12:32:47 PM
166
LESSON 13 Understanding scope
To save a value between method calls, you can change the variable into a field declared outside of
any method. The following version of the preceding code displays the values
1, 2, 3, and so on when
the user clicks the button multiple times:
// A field.
int count = 0;
private void clickMeButton_Click(object sender, EventArgs e)
{
count++;
MessageBox.Show(count.ToString());
}
Note that a parameter declared in a method’s declaration counts as having method scope. For example,
the preceding event handler has two parameters named
sender and e. That means you cannot declare
new variables within the method with those names.
Block Scope
A method can also contain nested blocks of code that define other variables that have scope limited
to the nested code. This kind of variable cannot have the same name as a variable declared at a higher
level of nesting within the same method.
Later lessons explain some of these kinds of nesting used to make decisions (Lesson 18), loops
(Lesson 19), and error handlers (Lesson 21).
A simple type of nested block of code that is described here simply uses braces to enclose code. The
scope of a variable declared within this kind of block includes only the block, and the variable is
usable only later in the block.
For example, consider the following code:
private void clickMeTooButton_Click(object sender, EventArgs e)
{
// A method variable.
int count = 1;
MessageBox.Show(count.ToString());
// A nested block of code.
{
int i = 2;
MessageBox.Show(i.ToString());
}
// A second nested block of code.
{
int i = 3;
MessageBox.Show(i.ToString());
}
}
This method declares the variable count at the method level and displays its value.
596906c13.indd 166 4/7/10 12:32:48 PM
Accessibility
167
The code then makes a block of code surrounded by braces. It declares the variable i and displays
its value. Note that the code could not create a second variable named
count inside this block
because the higher-level method code contains a variable with that name.
After the first block ends, the code creates a second block. It makes a new variable
i within that
block and displays its value. Because the two inner blocks are not nested (neither contains the other),
it’s okay for both blocks to define variables named
i.
ACCESSIBILITY
A field’s scope determines what parts of the code can see the variable. So far I’ve focused on the fact
that all of the code in a class can see a field declared at the class level, outside of any methods. In
fact, a field may also be visible to code running in other classes depending on its accessibility.
A field’s accessibility determines which code is allowed to access the field. For example, a class
might contain a public field that is visible to the code in any other class. It may also define a private
field that is visible only to code within the class that defines it.
Accessibility is not the same as scope, but the two work closely together to determine what code can
access a field.
Table 13-1 summarizes the field accessibility values. Later when you learn how to build properties and
methods, you’ll be able to use the same accessibility values to determine what code can access them.
TABLE 131
ACCESSIBILITY VALUE MEANING
public
Any code can see the variable.
private
Only code in the same class can see the variable.
protected
Only code in the same class or a derived class can see the variable.
For example, if the
Manager class is derived from the Person class,
a
Manager object can see a Person object’s protected variables.
(You’ll learn more about deriving one class from another in Lesson 23.)
internal
Only code in the same assembly can see the variable. For example, if
the variable’s class is contained in a library (which is its own assembly),
a main program that uses the library cannot see the variable.
protected internal
The variable is visible to any code in the same assembly or any derived
class in another assembly.
If you omit the accessibility value for a field, it defaults to private. You can still include the private
keyword, however, to make the field’s accessibility obvious.
The
private keyword sometimes causes confusion. A privateeld is visible to any code in any
instance of the same class, not just to the same instance of the class.
596906c13.indd 167 4/7/10 12:32:48 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.108.68