In Visual Basic, a module allows the declaration of variables and procedures that are accessible throughout the project (with the correct access modifiers). Variables declared inside a module outside of procedures become its fields – their visibility depends on the modifier (Private/Friend/Public), and their lifetime lasts throughout the application's runtime.
Key features of module variables:
Unlike global variables (for instance, in other languages or old VB6), module variables are not accessible outside the assembly unless explicitly declared as Public.
Example:
Module Globals Public Counter As Integer Sub Increment() Counter += 1 End Sub End Module ' Access to Counter from anywhere in the same project
Question: What access will a module variable have if declared with the Private modifier? Is it accessible from other modules of the same project?
Answer: No, a variable with the Private modifier is only accessible within this module – it cannot be accessed from other modules or classes.
Module Data Private x As Integer End Module ' Module Other will not see x
Story
When developing a calculation service, all values of intermediate results were stored in module variables. One of the developers assumed that the data would "reset" between calls, but the state persisted (Application Scope). This led to errors when multiple users used the service concurrently. Solution: use local variables and avoid maintaining state in modules if thread safety is required.
Story
In a multi-file project, a module variable was declared with the
Friendmodifier (instead ofPublic). It was expected that it would be accessible in all related projects of the solution, but it turned out to be visible only within a single assembly, causing unexpected access errors during the integration phase.
Story
After optimizing the code, the logical process flags stopped working because the class constructor was not passed the module where the static log flag is defined. As a result, the old version of the value was used, causing the system to work with outdated data, and the bug took a long time to investigate due to the difficulty in tracking the point of change of the module variable's state.