Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# handle command line args inconsistently?

In C#, getting command line arguments directly from Main() omits the exe name, contrary to the tradition of C.

Getting those same command line args via Environment.GetCommandLineArgs includes it.

Is there some good logical reason I'm missing for this apparent inconsistency?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(string.Format("args.Length = {0}", args.Length));

        foreach(string arg in args)
        {
            Console.WriteLine(string.Format("args = {0}", arg));
        }

        Console.WriteLine("");

        string[] Eargs = Environment.GetCommandLineArgs();
        Console.WriteLine(string.Format("Eargs.Length = {0}", Eargs.Length));
        foreach (string arg in Eargs)
        {
            Console.WriteLine(string.Format("Eargs = {0}", arg));
        }

    }
}

Output:

C:\\ConsoleApplication1\ConsoleApplication1\bin\Debug>consoleapplication1 xx zz aa 
args.Length = 3 
args = xx
args = zz 
args = aa
Eargs.Length = 4 
Eargs = consoleapplication1 
Eargs = xx 
Eargs = zz 
Eargs = aa
like image 474
MickeyfAgain_BeforeExitOfSO Avatar asked Dec 14 '10 17:12

MickeyfAgain_BeforeExitOfSO


1 Answers

Because it isn't C and thus isn't tied to it's conventions. Needing the exe name is pretty much an edge case; the small number of times I've needed this (compared to the other args) IMO justifies the decision to omit it.

This is additionally demanded in the spec (ECMA334v4, §10.1); (snipping to relevant parts):

10. Basic concepts

10.1 Application startup

...

This entry point method is always named Main, and shall have one of the following signatures:

static void Main() {…} 
static void Main(string[] args) {…} 
static int Main() {…} 
static int Main(string[] args) {…} 

...

• Let args be the name of the parameter. If the length of the array designated by args is greater than zero, the array members args[0] through args[args.Length-1], inclusive, shall refer to strings, called application parameters, which are given implementation-defined values by the host environment prior to application startup. The intent is to supply to the application information determined prior to application startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase. [Note: On systems supporting a command line, application, application parameters correspond to what are generally known as command-line arguments. end note]

like image 117
Marc Gravell Avatar answered Sep 19 '22 06:09

Marc Gravell