Projects with Multiple Modules

In our current example, notice that the Main() method is able to directly call the DisplayBanner() and GreetUser() methods. Because these methods are defined within the same module as Main(), we are not required to prefix the name of our module (Module1) to the member name. However, if you wish to do so, you could retrofit Main() as follows:

Sub Main()

' Show banner.


' Get user's name and say howdy.

Module1.GreetUser() End Sub

In the current example, this is a completely optional bit of syntax (there is no difference in terms of performance or the size of the compiled assembly). However, assume you were to define a new module (MyModule) in your project (within the same *.vb file, for example), which defines an identically formed GreetUser() method:

Module MyModule

Public Sub GreetUser()

Console.WriteLine("Hello user...") End Sub End Module

If you wish to call MyModule.GreetUser() from within the Main() method, you would now need to explicitly prefix the module's name. If you do not specify the name of the module, the Main() method automatically calls the Module1.GreetUser() method, as it is in the same module scope as Main():

Sub Main()

' Show banner.


' Call the GreetUser() method in MyModule.

MyModule.GreetUser() End Sub

Again, do understand that when a single project defines multiple modules, you are not required to prefix the module name unless the methods are ambiguous. Thus, if your current project were to define yet another module named MyMathModule:

Module MyMathModule

Function Add(ByVal x As Integer, ByVal y As Integer) As Integer

Return x + y End Function

Function Subtract(ByVal x As Integer, ByVal y As Integer) As Integer

Return x - y End Function End Module you could directly invoke the Add() and Subtract() functions anywhere within your application (or optionally prefix the module's name):

Sub Main()

' Add some numbers.

Console.WriteLine("10 + 10 is {0}.", Add(10, 10))

' Subtract some numbers ' (module prefix optional).

Console.WriteLine("10 - 10 is {0}.", MyMathModule.Subtract(10, 10)) End Sub

Note If you are new to the syntax of BASIC languages, rest assured that Chapter 4 will cover the details of building functions and subroutines.

Was this article helpful?

0 0

Post a comment