How would I declare a global variable in Visual Basic?

There are a couple of ways to do this in VB: a VB-specific way and a non-VB specific way (i.e. one that could also be implemented in C#.

The VB-specific way is to create a module and place the variable in the module:

Public Module GlobalVariables
   Public MyGlobalString As String
End Module

The non-VB-specific way is to create a class with shared properties:

Public Class GlobalVariables
  Public Shared Property MyGlobalString As String
End Class

The primary difference between the two approaches is how you access the global variables.

Assuming you are using the same namespace throughout, the VB-specific way allows you to access the variable without a class qualifier:

MyGlobalString = "Test"

For the non-VB-specific way, you must prefix the global variable with the class:

GlobalVariables.MyGlobalString = "Test"

Although it is more verbose, I strongly recommend the non-VB-specific way because if you ever want to transition your code or skillset to C#, the VB-specific way is not portable.


IN VB6 just declare on top code

public GlobalVariable as string

then you can use GlobalVariable in any form as you like.

like

GlobalVariable = "house"

then you can use /call in other form

text1 = GlobalVariable

will show value "house"

Tags:

Vb.Net