Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to read commandline parameters in console application

Below are two ways of reading in the commandline parameters. The first is the way that I'm accustom to seeing using the parameter in the main. The second I stumbled on when reviewing code. I noticed that the second assigns the first item in the array to the path and application but the first skips this.

Is it just preference or is the second way the better way now?

Sub Main(ByVal args() As String)
    For i As Integer = 0 To args.Length - 1
        Console.WriteLine("Arg: " & i & " is " & args(i))
    Next

    Console.ReadKey()
End Sub



Sub Main()
    Dim args() As String = System.Environment.GetCommandLineArgs()

    For i As Integer = 0 To args.Length - 1
        Console.WriteLine("Arg: " & i & " is " & args(i))
    Next

    Console.ReadKey()
End Sub

I think the same can be done in C#, so it's not necessarily a vb.net question.

like image 390
osp70 Avatar asked Sep 17 '08 12:09

osp70


People also ask

How do I access command line arguments?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments.

How do you pass or access command line arguments in C#?

How to Pass or Access Command-line Arguments in C#? In C#, the Main() method is an entry point of the Console, Windows, or Web application (. NET Core). It can have a string[] args parameter that can be used to retrieve the arguments passed while running the application.

How do I pass a command line argument in Visual Studio?

To set command-line arguments in Visual Studio, right click on the project name, then go to Properties. In the Properties Pane, go to "Debugging", and in this pane is a line for "Command-line arguments." Add the values you would like to use on this line. They will be passed to the program via the argv array.


1 Answers

Second way is better because it can be used outside the main(), so when you refactor it's one less thing to think about.

Also I don't like the "magic" that puts the args in the method parameter for the first way.

like image 147
David Thibault Avatar answered Sep 18 '22 03:09

David Thibault