Command Line Arguments

To successfully run a C# application, you must provide a Main method. The  Main() method is the starting point of the program. It is declared public or internal,  and it must also be static. You can actually pass command line arguments to the Main() method. This is  demonstrated by the code below.

using System;

namespace CommandLineArgumentsDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            string name = args[0];
            int counter = Convert.ToInt32(args[1]);

            for (int i = 1; i <= counter; i++)
            {
                Console.WriteLine(name);
            }
        }
    }
}

Example 1 – Command Line Arguments

Notice the parameter args. It is a string array that can accept any number of string arguments. If you build your program and access the .exe file for your program, you can pass string parameters to the Main. For example, open the command prompt, and access your .exe file by moving to the directory where it exists. Below only shows an example but the directory might be different for you. Suppose our .exe is located in C:\Sample Project\bin\Release\.

C:\Sample Project\bin\Release\Sample Bob 5
Bob
Bob
Bob
Bob
Bob

We execute the file by writing its file name. After it, we wrote Bob and 5. The first one will be stored in the first element of array args and the second one will be stored in the second element. The code inside the  Main() method does the rest of the job. We stored the first element of args to a variable and we converted the second element of args into int and stored it in an int variable. We then print the name x times by using a for loop.

In fact, many program uses this technique. You can pass command line arguments to modify how a program runs. For example, you can activate a cheat code when you run a game through the command line.