C Sharp

Command-Line Arguments

You can access the command-line arguments to an application by declaring the Main method as taking a string array type as its only argument. At that point, the arguments can be processed as you would any array. Although arrays won't be covered until Chapter 7, here's some generic code for iterating through the command-line arguments of an application and writing them out to the standard output device: -

using System;
class CommandLineApp
{
    public static void Main(string[] args)
    {
        foreach (string arg in args)
        {
            Console.WriteLine("Argument: {0}", arg);
        }
    }
}

And here's an example of calling this application with a couple of randomly selected values: -

e:>CommandLineApp 5 42
Argument: 5
Argument: 42

The command-line arguments are given to you in a string array. To process the parameters as flags or switches, you'll have to program that capability yourself.

NOTE
Developers in Microsoft Visual C++ are already accustomed to iterating through an array that represents the command-line arguments to an application. However, unlike Visual C++, the array of command-line arguments in C# does not contain the application name as the first entry in the array.

Return Values

Most examples in this tutorial define Main as follows: -

class SomeClass
{
    image
public static void Main()
{
    image
}
    image
}

However, you can also define Main to return a value of type int. Although not common in GUI applications, this can be useful when you're writing console applications that are designed to be run in batch. The return statement terminates execution of the method and the returned value is used as an error level to the calling application or batch file to indicate user-defined success or failure. To do this, use the following prototype: -

public static int Main()
{
image
    // Return some value of type int
    // that represents success or value.
    return 0;
}

by BrainBellupdated
Advertisement: