A more .NETish main()

In VC++.NET 2005 Beta 2, if you create a new .NET console app project (now aptly called a CLR console app in the wizard), you’ll see that the generated main() function is prototyped thus :-

int main(array<System::String ^> ^args)

That’s rather neat – considering that we are using .NET, it makes sense to have a String array passed to us rather than an array of char*s or a char** (whichever way you like to look at it).

Test out the following code :-

int main(array<System::String ^> ^args)
{
    Console::WriteLine("Number of args {0}", args->Length);
    int count = 0;
    for each(String^ s in args)
    {
        Console::WriteLine("Argument {0} = {1}",count++,s);
    }
    return 0;
}

Run it following the output shown below :-

>B2_Properties.exe interesting
Number of args 1
Argument 0 = interesting

>B2_Properties.exe hello world
Number of args 2
Argument 0 = hello
Argument 1 = world

>B2_Properties.exe
Number of args 0

Hmmm, a slight difference from the way our traditional main(int argc, char** argv) behaved. The filename is not counted as an argument, so an app run without parameters has zero arguments passed and the String array is empty. I suppose they had to do it this way to be compatible with C# (which I believe does it this way).

Advertisements

6 thoughts on “A more .NETish main()

  1. When you are writing a CLR Console application I assume – since I don’t have VSTS B2 yet, just the express editions of C# and VWD – the change was made so that by default you got a verifiable application.

    The definition of the entry point is also that defined by the CLI and not C# nor VB.NET, the int main( array<System::String^> ^args ) prototype is just the C++/CLI version of the standard entry point for a .NET application.

    I’m sure if you were to use the C++ standard main function then the app would no longer be verifiable…Though I would feel better if someone would test that to be sure.

  2. There is a good reason the filename is not counted as an argument. This information can easily be obtained from Environment::CommandLine or the Process class (I believe). The filename is really not important to most applications nor is it technically an argument.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s