Modules (Module) in Visual Basic are historically used to store procedures, functions, and variables accessible throughout the entire project without the need to explicitly create an instance. With the introduction of classes, their roles have partially overlapped, but significant differences remain.
Background:
In classic Visual Basic (VB6), modules were the only way to group common functions and global variables. In VB.NET, modules remain, but with enhanced capabilities of classes.
Issue:
A developer may not understand the difference between a module and a class, leading to incorrect choices about where to store logic, accidental code duplication, or unexpected behavior of variables.
Solution:
The choice between a module and a class depends on the goals:
Example code:
' Module Module MathUtils Public Function Add(x As Integer, y As Integer) As Integer Return x + y End Function End Module ' Usage Dim result = MathUtils.Add(5, 10)
Key features:
Shared and accessible without an instanceIf a variable is declared in a module as Public, will it be global for all forms/classes of the application?
Yes. Public variables in a module are essentially global. They are accessible from any code in the project, which is convenient, but may lead to errors in multithreading or accidental overwriting of values.
Can a module instance be created using New?
No. Modules are not instantiated. All their functionality is accessed statically.
Can a module be inherited or declared with Protected or Private access modifiers?
No. Modules cannot be inherited and are only declared at the namespace level, cannot be nested, or have other access modifiers besides Public or Friend.
In the project, all user state variables are declared as Public in a module. With any change in value in one form, it instantly becomes new for all others.
Pros:
Cons:
A module is used only for storing auxiliary utilities (e.g., conversion functions), while user state is stored in classes with encapsulation.
Pros:
Cons: