Total .NET Analyzer Rule Documentation  

UseOfVBModule Rule

When possible, use a class instead of a VB module.

Remarks

In previous version of Visual Basic, it was perfectly appropriate to use modules when you needed a structure to be shared (or Static). For instance, your code may implement the following module:


Module NewModule
Public Function SquareNum(ByVal x As Double) As Double
Return x ^ 2
End Function
End Module

The module would be called in code without instantiating the object:

Console.WriteLine(SquareNum(10))


Visual Basic .NET, however, includes the "Shared" keyword, which eliminates most practical uses of modules. Consider replacing modules with classes whenever possible.

Using Classes in place of modules has several advantages, including:
- Classes allow more flexibility than modules. They allow inheritance, property declaration, and interface implementation.
- Classes can be instantiated. This means that variable data exists separately for each instance of the class. Module variables, on the other hand, are like global variables in that they exist for the lifetime of the program. If a variable is modified in one part of the application, the change persists throughout the lifetime of the program.
- Classes require less system resources, increasing the performance of your applications. When you use modules, all functions and methods are loaded into memory throughout the life of the application. Class functions and methods are only loaded into memory for the life of the class instance.
- Class declarations can be nested within other types. Modules, on the other hand, can only be declared in a namespace.
- Modules are not supported in other .NET languages, such as C#.

Resolution

You should consider replacing VB modules with Classes whenever possible. For instance, you could modify the code above to serve the same function as the module by creating a class with a shared function:

Class NewClass
Public Shared Function SquareNum(ByVal x As Double) As Double
Return x ^ 2
End Function
End Class

Shared classes do not have to be instantiated, but the class name does have to be referenced:

Console.WriteLine(NewClass.SquareNum(10))


Note that if you do not use the Shared keyword, the class needs to be instantiated:

Dim o As New NewClass()
Console.WriteLine(o.SquareNum(10))

See Also

Classes vs. Standard Modules

Inheritance Basics

Interfaces