No, I’m not referring to a common brand of mouthwash. In programming, “Scope” refers to the visibility of a variable, as seen from different locations of a program. Not all variables and objects are available for use by any procedure; that would be akin to a hotel room that leaves all of its doors unlocked, allowing anyone to modify the contents of a room!

Procedure-Level Scope

The simplest form of scope is on a procedural level. Say you’re writing a C# program that, inside of a method or subroutine function, defines a String object:

From anywhere other than the scopeExample subroutine, the cantTouchThis String would be inaccessible.

Module-Level Scope

Sometimes, variables are defined inside of a class. Often you want to be able to talk to these variables from outside of the class’s declaration, but sometimes you want them to stay hidden, or private. How would you do this? Take a look at this code:

From outside of the above code, you would be able to view the usersAge variable to see the user’s age, because it is public. However, you would not be able to view the netWorth variable, because it has been declared as private.

On the other hand, because the makeUserRich subroutine is declared as public, you would be able to do the following from somewhere else in your program:

This is a fairly simple explanation of scope, and how it can be used to protect members of your program. More advanced topics will be discussed later, however having a solid understanding of these concepts will lay a greater foundation for those more advanced topics.

Share

Comments are closed.

Post Navigation