Program Entry Points                                                      
                 
Every program needs to start somewhere. In VB, this “somewhere” is either Sub Main or Function Main. VB
requires exactly one Shared procedure called Main(). In some cases, the VB compiler creates a Main() behind the
scenes. You’ll see an example of that when you study Windows Forms.

All the previous code examples have defined Main() as a subroutine within a Module. A Module is simply a
way to group logically related functions and data. Every method or field defined within a Module is implicitly
Shared. Therefore, the following code defines a perfectly acceptable version of Main:


Module MyModule
  
   Sub Main()
      'Program starts here
   End Sub

End Module


Main() does not have to be in a module. You can put it in a class, as long as you remember to mark it as Shared.


Class SomeClass
   Shared Sub Main()
      'Program starts here.
   End Sub
End Class


Console applications typically allow the user to provide arguments on the command line. You can access the
command line arguments using the Environment class, which provides a shared GetCommandLineArgs method.
The Environment class is similar to VB6’s App object.


 Module MyModule

   Sub Main()
      Dim arg As String
      For Each arg In Environment.GetCommandLineArgs()
         Console.WriteLine(arg)
      Next
   End Sub

 End Module

Alternatively, you can define Main() to accept the command line as an input parameter:

Module MyModule

   Sub Main(ByVal CmdArgs() As String)
      Dim arg As String
      For Each arg In CmdArgs
         Console.WriteLine(arg)
      Next
   End Sub

End Module


Finally, Main() can be defined as a function instead of a sub. In this case, Main() returns an integer representing
an exit code. OS uses the exit code to determine whether the application was successful. Typically, returning 0
indicates success. Any other value indicates failure.


Module MyModule
   Function Main() As Integer
      Dim arg As String
      For Each arg In Environment.GetCommandLineArgs()
         Console.WriteLine(arg)
      Next
      Return 0
   End Function
End Module



Module MyModule
   Function Main(ByVal CmdArgs() As String) As Integer
      Dim arg As String
      For Each arg In CmdArgs
         Console.WriteLine(arg)
      Next
      Return 0
   End Function
End Module
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Entry Points
Table of Contents
Courseware
Training Resources
Tutorials
Services