Home
VB.NET
Module Example
Updated Nov 25, 2023
Dot Net Perls
Module. In VB.NET, a Module is not a class—it is a container element, but is not an object. In a Module, all members are shared and have "Friend" accessibility.
Some notes. We cannot instantiate a Module—it serves mainly to organize code in a global, single place. It is similar to a namespace or static class in other languages (such as C#).
Class
This example uses 2 modules. By default, the Sub Main is placed in a Module called "Module1." This is where control flow begins in a VB.NET program.
Info This module has a field, _value, which is shared automatically (implicitly). So the field has only one instance.
Note In Module2 we see a Sub called Increment. This is by default "Friend." It can be easily accessed from Main.
Note 2 When Increment is called, the field _value is changed. This change persists throughout uses of Increment.
Important This demonstrates that the field is shared, even though it has no shared keyword.
Shared
Module Module1 Sub Main() ' Use Module2. ' ... It does not need to be created. Module2.Increment() Module2.Increment() Module2.Increment() End Sub End Module Module Module2 Dim _value As Integer Sub Increment() ' The value is shared. Console.WriteLine(_value) ' Change the value. _value += 1 End Sub End Module
0 1 2
Error. We cannot instantiate an instance of a Module. There is no "New" Sub on it. A Module is not a type, but rather an organizational namespace for programs that is shared.
Warning If you try to create a Module, you will get an error. Please consider adding a class to fix this problem.
Module 'Module2' cannot be used as a type.
Discussion. A Module has many rules. For example, it cannot inherit from another module. And you cannot specify the shared keyword on any of its members (they are already shared).
Summary. Modules are common in VB.NET. But more complex data structures are not built with many modules—rather they use classes as building blocks. A module is an organizational construct.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 25, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen