Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Scope

When you create a variable with a declaration statement, .NET allocates enough memory to store the specified type’s properties and makes the identifier you’ve declared available for use. But declared elements don’t last forever, and you can’t access them from anywhere. The rule is simple: A variable is only visible within the context in which it’s defined. It’s a simple rule, so let’s look at a simple example:

image

How’d You Do?

image

image


Put on Your Thinking Hat

image

Scope really is a pretty simple principle, but there are a couple of places you can manage to confuse yourself. Let’s take a look at the two most common:

image


How’d You Do?

image

image


Best Practice—Variable Names

image

Beware! The variable names a,b, c and x, y, z are dangerous. It’s customary to use them as the control variable of a loop, as I’ve done here, but they don’t tell you anything but that they’re a control variable. If you’re going to use them for any other purpose, you should choose a more descriptive name (even if it’s only loopCounter).


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint