Scope

Scope - Where variables are declared and how that affects their use.

Whether variables are accessible or not – Their Scope - depends on how and where they are declared.

Within a Class Module variables may be declared in

If declared within a procedure with a Dim statement the variable is Local to that procedure. The variable is known only to that procedure and cannot be used by any other procedure.

Private Sub btnAdd_Click(………….)
      Dim intNumber As Integer
     

      intNumber = intNumber + Convert.ToInt32(txtNumber.Text)
     
End Sub

What do you think will happen if you attempt to access a variable declared in a different procedure?

Private Sub btnReportTheNumber_Click(……)
      MsgBox( intNumber)
End Sub


If declared in the Declarations Section of the Form Module with a Dim statement the variable is called a Class Level variable and known to all procedures in the form module. It is local to the Class.

 

**************Demo Procedural vs. Class level variables


All procedural variables (those defined within a procedure) are Dynamic unless otherwise specified. Dynamic means they removed from memory when the procedure ends and are reinitialized to the default or assigned value every time the event procedure is invoked.

**************Demo Dynamic variable

To make a variable retain its value from the previous time the procedure was called we could declare it as Static

Private Sub btnReport(..........)
    
Static intNumber As integer


     intNumber = intNumber + 5
     intNumber = intNumber + Convert.ToInt32(txtNumber.Text)

End Sub

***********Demo Static variable

A static variable is still local to the procedure in which it was declared that is it is known only to that procedure and cannot be used by any other procedure.

Form level variables are by default Static. They remain in memory throughout execution of the program.

If declared within a code block the variable is Local to that code block. The variable is accessible only within the code block and cannot be used outside of the block.

Private Sub btnAdd_Click(………….)
      If IsNumeric(txtNumber.Text) Then

Dim intNumber As Integer

intNumber = Convert.ToInt32(txtNumber.Text)
     

             intNumber = intNumber + 5
             MsgBox( intNumber)
    
End If

     MsgBox(intNumber)
End Sub

 

***********Demo Scope - Code Block

 

The concepts of local variables allows for the same name to be used for different variables (different areas of memory) within a project.

If a Class level variable has the same name as a procedure level variable the procedure level variable is used.

It is generally advised to limit the scope of a variable to the smallest possible range.