Variable scope in Visual Basic

In our tutorials so far, we have used variables to store and retrieve named values.   We’ve  typically executed this code in the the Form Load Event, and it wasn’t until the last tutorial on subroutines and functions that we started to split our code into units.  If you remember, we used Subroutines and Functions to write super-efficient code, obeying the DRY (Don’t Repeat Yourself) Principle to help make our code as maintainable as possible.  This all leads us very nicely to today’s tutorial, taking our knowledge of these two crucial concepts onto the next level.  In this tutorial, we will learn, by example, how to efficiently use variable scope to our advantage and extend our already honed ability to write elegant, maintainable and efficient code.

So what exactly is variable scope?  A variable, if you remember, is a named value you can commit to your application’s memory.

Dim myVariable as String

myVariable = “This is the value of the variable”

The term variable scope defines when the variable is in memory.  A variable is in scope when it’s value is accessible by your code.  You can write to it and read from it without Visual Basic kicking up a fuss.  .  When a variable is out of scope, it can’t be accessed.  This means you can’t read or write to the variable at all.  As far as Visual Basic is concerned, the variable doesn’t even exist!

Variable scope defines when a variable can be accessed.

Let’s look at the example from the tutorial on Subroutines and Functions to see how a variable can be considered in or out of scope.  If you remember, we created a function to calculate the area of a circle.  The code looked as follows:

Dim radiusOne as Double
Dim areaOne as Double
Dim radiusTwo as Double
Dim areaTwo as Double

radiusOne = 3
radiusTwo = 2

areaOne = CalculateArea( radiusOne )
areaTwo = CalculateArea( radiusTwo )

Private Function CalculateArea (ByRef radius as Double) As Double

Dim pi as Double

     pi = 355/113

     CalculateArea  = pi * radius ^ 2

End Function

In the Function CalculateArea there is a variable called pi.  What happens if I tried to access the value of pi outside of the Function CalculateArea as so?

MessageBox.Show( pi )

Private Function CalculateArea (ByRef radius as Double) As Double

     Dim pi as Double

     pi = 355/113

     CalculateArea  = pi * radius ^ 2

End Function

Try it and see.  What happens when you try to run the above code?  You’ll get a compilation error. Visual Basic can’t execute your program as you have a problem with your code.  The program won’t run.  If like me, you’re using Visual Studio 2010 for this example, the compilation error you’ll get is “’pi’ is not declared. It may be inaccessible due to its protection level.”  The Visual Studio 2010 compiler, in its own inimitable way, is saying that the variable can’t be accessed.  It’s saying that the variable is out of scope.

In the above example, pi is only in scope where it is defined.  In this case, the Dim statement appears in the Function CalculateArea.  This tells Visual Basic that this variable is local to that Function and is not accessible anywhere else in the application.  It is only in memory when that Function is being executed.  As soon as Visual Basic leaves the Function, it completely discards the variables declared in the Function.

One solution to this problem would be to move the the declaration of the variable outside the Function as so:

Dim pi as Double

MessageBox.Show( pi )

Private Function CalculateArea (ByRef radius as Double) As Double

     pi = 355/113

     CalculateArea  = pi * radius ^ 2

End Function

This would work.  Well, the compiler wouldn’t complain anyway.  However the variable pi wouldn’t be populated when the MessageBox is shown.  pi isn’t populated until the Function CalculateArea is called.

In the old VB6 days, to avoid having variables out of scope we could make all the variables global.

Global pi as Double

Declaring a variable as Global meant the variable could be accessed anywhere in your application.  The variable is Global in scope as opposed to Local in scope (when it is declared in a Function or Subroutine).

This may sound like a great idea and it was a great idea to many VB programmers, some of whom made all variables Global.  They didn’t have to worry about variable scope at all!   They also quickly found their applications didn’t work.   When their applications grew in scale they inevitably ran into memory issues.  Think of what happens when you declare a variable.  Visual Basic allocates an amount of space in memory for that variable.  That memory is finite, and if you keep allocating space with more and more Global variables, that memory will eventually run out.

You should always have variables in scope as long as they are needed, but no longer.  This is an absolutely essential discipline.  It may seem like a pain now but as you practise more and more it become second nature.

As an aside, do you know, we had already discussed variable scope in a previous tutorial?

Look at the example again:

areaOne = CalculateArea( radiusOne )
areaTwo = CalculateArea( radiusTwo )

Private Function CalculateArea (ByRef radius as Double) As Double

Dim pi as Double

     pi = 355/113

     CalculateArea  = pi * radius ^ 2

End Function

We were able to access the variables radiusOne and radiusTwo in the Function CalculateArea even though they weren’t declared there.  We passed these variables as parameters to the Function.  Using parameters in our Functions and Subroutines is an efficient way to keep memory usage to the minimum.  It allows us to declare variables in one routine and access them in another.  The variables are in scope when they needed to be in scope….and no longer.

You were already adept at utilising efficient variable scope and you didn’t know it.