Reputation: 73
I'm trying to set a global variable in Visual Studio, but I can't make it static. Is there any way for me to set the variable as static and share it across different methods, or some way to save the variable each time it changes?
Upvotes: 5
Views: 26899
Reputation: 27342
You have two options:
1 - Create a class that contains a Shared variable (this is the same as a static variable in C#)
Public Class GlobalVariables
Public Shared Bar As String
End Class
You can then access this using the class name:
GlobalVariables.Bar = "Hello world"
2 - Create a module (this is akin to a static class in C#)
Public Module GlobalVariables
Public Bar As String
End Module
You can then access this value in code like this:
Bar = "Goodbye cruel world"
Upvotes: 11
Reputation: 575
If you use the number 1 option presented by @Matt Wilko, you can reference the shared member either through an object instance of the class or by referencing the class without an object reference. Both point to and increment the same variable and therefore reference the same value. Although, the Visual Studio compiler provides a warning about referencing an object instance and says that it will not be evaluated, it still compiles. The compiler's recommendation is to use the class name.
Public Class GlobalVariables
Public Shared Foo As Integer
End Class
Insert the following into a form and call IncrementIntegers() from a button click event procedure and you will find that myGlobalVariables.Foo and GlobalVariables.Foo both return 20.
Private Sub IncrementIntegers()
Dim myGlobalVariables As New GlobalVariables
myGlobalVariables.Foo = 0
GlobalVariables.Foo = 0
myGlobalVariables.Foo += 10
GlobalVariables.Foo += 10
Dim iLocalInt1 = myGlobalVariables.Foo
MessageBox.Show("myGlobalVariables.Foo = " & iLocalInt1.ToString)
Dim iLocalInt2 = GlobalVariables.Foo
MessageBox.Show("GlobalVariables.Foo = " & iLocalInt2.ToString)
End Sub
Note that with option 1, Foo must be qualified with either the class name or an object name. With option 2, it is a module and not a class so an object reference cannot be created. The public variable can be referenced without qualifying it with the module name unless a variable with the same name appears in another module in which case the compiler with throw a name conflict error. For example,
Public Module1
Public Foo As String
End Module
Public Module2
Public Foo As String
End Module
Remove Module2 and Foo can be called unqualified from anywhere.
Foo = "Happy birthday"
With Module2 present, Foo must be qualified with the name as both point to different variable and represent different and independent values.
Module1.Foo = "Goodbye cruel world"
Module2.Foo = "Hello new world"
Upvotes: 1