C# Command Line Argument

In this chapter you will learn:
  • What is Command Line Argument in C#?
  • What is the functionality of command line argument?
  • How to use command line argument in C# programming?

We all know, that we can pass the parameter to a function as an argument but what about Main(string[] args) method? Can parameters be passed to Main() method in C#? Yes, parameter(s) can be passed to a Main() method in C# and it is called command line argument.

Main() method is where program stars execution. The main method doesn’t accept parameter from any method. It accepts parameter through the command line. It is an array type parameter that can accept n number of parameters at runtime.

In Main(string[] args), args is a string type of array that can hold numerous parameter.

Programming Example of Command Line Arguement

To understand command line argument in C#, consider the following command line example.

1. Open Notepad and write the following code and save it with command.cs

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace command
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("First Name is " + args[0]);
            Console.WriteLine("Last Name is " + args[1]);
            Console.ReadLine();
        }
    }
}

2. Open visual studio command prompt and compile the code as follow:
(i) Set current path, where your program is saved.
(ii) Compile it with csc command.cs

3. Now execute the program using following command line argument:
(a) command steven clark

Output


Setting environment for using Microsoft Visual Studio 2008 x86 tools.
C:\Program Files\MIcrosoft Visual Studio 9.0\VC>d:

D:\>csc command.cs
Microsoft <R> Visual C# 2008 Compiler version 3.5.30729.1
for Microsoft <R> .NET Framework version 3.5
Copyright <C> Microsoft Corporation. All rights reserved.

D:\>command STEVEN CLARK
First Name is STEVEN
Last Name is CLARK
__

In the preceding example, we passed two parameters STEVEN CLARK as command line argument to the main method. In runtime, Main() method accepted both parameters and holds it to the args variable that is string type array. Then both values are accessed with the index position of array.

Summary

In this chapter you learned about command line argument in C#. You also learned how to use it in programming. In next chapter there are some  programmings examples are given for you.

 

Share your thought