The easiest way to think about scope is that a variable has the scope of the block it is declared in.
Blocks are defined by opening and closing curly braces. A variable declared in the class block has class scope. It can be seen and used by any method in the class. A variable that has method scope can be seen and used by any command in the method. A variable that has block scope, such as in an if block or a loop,
can only be accessed from within that block.
Below is example of various scopes: (it is not a real program and won't run. It is just to show the levels of scope.)
class program
{
int number; //class scope
static void Main()
{
string name; //method scope
number=0;//changing the class level variable
while (number==0)
{
int counter=1; //block scope
}
}
}
A couple of other things to note. If you name two variables the same, the one with the smaller scope takes precidence. That means if I have a class level variable named number, and I name a variable in one of my methods number, the variable is given method level scope for the duration of the method,
There are some exceptions to the general scope rule but we will deal with them as we encounter them.
General Principle
Give any variable the most limited scope possible, while still enabling it to do what it needs to do.
No comments:
Post a Comment