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:
1 2 3 4 |
void scopeExample() { String cantTouchThis = “This string cannot be used outside of this procedure.” } |
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:
1 2 3 4 5 6 7 8 9 10 11 |
class BankAccount { public double usersAge = 24.5; private double netWorth = 12345.67; public void makeUserRich() { // If user is above 30 years old, add $100,000 to their account if (usersAge > 30) { netWorth += 100000; } } } |
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:
1 2 3 |
BankAccount bigSavingsAccount = new BankAccount(); bigSavingsAccount.makeUserRich(); // User now has $112,345.67. |
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.