C# Command Line Arguments

By default, the 'Main' method within a C# program, has one parameter, called 'args', which is an array of strings.

class Program
{
    static void Main(string[] args)
    {

    }
}

This allows for the acceptance of command line arguments, when a program is called from the command line, as previously discussed, or via a batch file. Below is an example of how a program called 'DemoConsole.exe' can be called with four arguments, in this case first name, last name, title and date of birth.

.\DemoConsole.exe Bob Smith Mr 1980-01-20

As the arguments are separated by spaces, if a space is included within an argument, it would need to be wrapped in quotes. From within the program, these can be accessed via the 'args' array, in the order that the arguments were specified.

static void Main(string[] args)
{

    Console.WriteLine(args[0]);
    Console.WriteLine(args[1]);
    Console.WriteLine(args[2]);
    Console.WriteLine(args[3]);

}

This will produce the following output to the console.

Bob
Smith
Mr
1980-01-20

In order for these arguments to be accessible to the whole class, it is necessary to assign them to variables.

class Program
{

    private static string firstname;
    private static string lastname;
    private static string title;
    private static DateTime dob;

    static void Main(string[] args)
    {

        firstname = args[0];
        lastname = args[1];
        title = args[2];

        if (!DateTime.TryParse(args[3], out dob))
        {
            Console.WriteLine("The date of birth is invalid.");
            System.Environment.Exit(1);
        }

        Console.WriteLine(firstname);
        Console.WriteLine(lastname);
        Console.WriteLine(title);
        Console.WriteLine(dob);

    }

}

One thing to note here is with the date of birth. As the 'args' array contains string values, this argument has to be converted, or parsed, in order for it to be stored in the 'DateTime' variable. Here, the 'if' statement tries to do this task. If it is unsuccessful, a message is displayed and execution of the program stops.

Once the arguments have been assigned to variables, they are accessible throughout the class.

Further Resources