The Role of the Module Type

Visual Basic 2008 supports a specific programming construct termed a module, which is declared with the Module keyword. For example, when you create a Console Application project using Visual Studio 2008, you automatically receive a *.vb file that contains the following code:

Module Module1 Sub Main() End Sub End Module

Under the hood, the Module keyword defines a class type, with a few notable exceptions. First and foremost, any public function, subroutine, property, or member variable defined within the scope of a module is exposed as a "shared member" that is directly accessible throughout an application. Simply put, shared members allow you to simulate a global scope within your application that is roughly analogous to the functionality provided by a VB6 *.bas file (full details on shared members can be found in Chapter 5).

Given that members in a module are directly accessible, you are not required to prefix the module's name when accessing its contents. To illustrate working with modules, create a new Console Application project (named FunWithModules) and update your initial code file as follows:

Module Module1 Sub Main() ' Show banner.


' Get user's name and say howdy.

GreetUser() End Sub

Sub DisplayBanner()

' Get the current color of the console text.

Dim currColor As ConsoleColor = Console.ForegroundColor

' Set text color to yellow.

Console.ForegroundColor = ConsoleColor.Yellow Console.WriteLine("******* Welcome to FunWithModules *******") Console.WriteLine("This simple program illustrates the role") Console.WriteLine("of the Module type.")


' Reset to previous color of your console text.

Console.ForegroundColor = currColor Console.WriteLine() End Sub

Sub GreetUser() Dim userName As String Console.Write("Please enter your name: ") userName = Console.ReadLine()

Console.WriteLine("Hello there {0}. Nice to meet ya.", userName) End Sub End Module

Figure 3-1 shows one possible output.

j C:\Windows\system32\cmdexe

******* Welcome to FunWithModules ******* This simple program illustrates the role of the Module type.

Please enter your name: Mikko the Wonder Cat Hello there Mikko the Wonder Cat. Nice to meet ya.

Figure 3-1. Modules at work

Was this article helpful?

0 0

Post a comment