It’s about time that we look more closely at the topic of variable scope. Variable scope can be summarized as follows: variables that are initially declared in any given code block (designated by squiggly brackets) are available for reference within that code block, as well as code blocks inside of that block. However, the opposite is not true: variables declared within an inner code block are not available to outer code blocks. In other words, a code block can reach out and grab an outer code block’s variable, but it can’t reach in and grab an inner code block’s variable.
Let’s set up a simple demonstration of this by creating a new ASP.NET project called “CS-ASP_024” with a Button Control that has a programmatic ID called “okButton”:
Whenever you (1) first declare a variable within a given code block it is said to belong to that scope. Here, x is scoped local to the okButton_Click event and is, therefore, available (2) anywhere within the okButton_Click event, including (3) inner code blocks:
As mentioned, however, you cannot do the reverse and reach into inner scopes to access inner-scoped variables:
In fact, you will notice that Intellisense can’t even recognize the y variable outside of the scope that it was originally declared. If you insist on trying to access it anyways, Intellisense will provide you with this error message when hovering over the inaccessible variable (you can exchange the word “context” for “scope”):
When you declare the variable at the class level (scope), it becomes accessible to all of the inner scopes (including inner-inner scopes, inner-inner-inner scopes, and so on). Again, this is perfectly acceptable because inner scopes can reach out and grab any variable from any scope outer to it:
It may be better to visualize the various scope levels with the following representation:
Scope becomes a bit more interesting, and complex, when you begin to learn about Object-Oriented Programming. However, for now the outer-most scope you will be concerned with is that of the class level. We'll be talking about classes much more in the future, but for now just keep that in mind.
Lesson 24 - Understanding Variable Scope