Command Line Arguments in C#

In C# we can define two types of classes, one that has a Main() method and another without a Main() method. When we define a class with a Main() method, it is the entry point of our executable program for the application. The second type of class is used to build a class library for building application features.

1. Create a Console Application

Go to "File" -> "New" -> "Project...". The "New Project" window will appear, as in:

3.png

Click on the "OK" button and create a project with a solution.

2. Main Method

The Main() method is an entry point for execution program. Each execution program contains at least one Main() method. In our project default a Program class creates in Program.cs file.

4.png

3. Create Executable Program 

The following Program is an executable program that is showing arguments on command.

using System; 
namespace CommandLineApplication
{
    class
Program
    {
        
static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("Arguments Values are {0}", args[i]);
            }
            Console.Read();
        }
    }
}

4. Pass Command Line Argument Using VS2010

Right-click on "Project" -> "Properties". Then in the right panel is "Debug"; enter arguments into the Command line arguments textbox.

consoleapp.png

5. Pass Command Line Arguments using Run window 

Pass the full path of the executable application with arguments and each argument is separated by a single blank space.

1.png

6. Output

2.png

Up Next
    Ebook Download
    View all
    Learn
    View all