Main
, argsOften developers may need to run a VB.NET program as a command-line utility. And in this situation, the program usually must accept command-line arguments.
By specifying a string
array argument to Main
, the program will automatically receive arguments. We can then loop over the array and act upon its elements.
To begin, the Main
method is specified as a Sub
, as it does not return a value. It is contained in a Module
—the name of the module is not important.
String
array, and thus it has a Length
property we can test and print.For-Each
loop to enumerate the elements in the string array. The file name is not included.Select Case
—or any other VB.NET construct—to test and handle the String
elements.Module Module1 Sub Main(args as String()) ' Step 1: print length of array. Console.WriteLine("Args length is: {0}", args.Length) ' Step 2: loop over each argument. For Each arg in args ' Step 3: print argument and use Select Case to match it. Console.WriteLine("Arg is: {0}", arg) Select Case arg Case "test" Console.WriteLine("TEST ARG") Case "test2" Console.WriteLine("TEST2 ARG") Case Else Console.WriteLine("Unknown") End Select Next End Sub End Moduledotnet run test test2 Args length is: 2 Arg is: test TEST ARG Arg is: test2 TEST2 ARG
In my testing, the args array is never Nothing, even when zero arguments are present. However, it may be worth testing it with IsNothing
, depending on where the program will run.
Even though VB.NET is a good choice for programs with Windows Forms user interfaces, it can be used for console programs. And for simple tasks, console programs are an ideal choice.