C# Command Line Argument

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 parameter to a function as argument but what about Main(string[] args) method? Do parameters can 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. Main method doesn’t accept parameter from any method. It accept parameter through command line. It is an array type parameter that can accept n number of parameter in 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.

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

  • 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.


    2 thoughts on “C# Command Line Argument”

    1. One way to pass parameters is to right click on your project and select properties.In that select Debug there you will find Command Line Arguments box.Pass as many arguments you want.
      NOTE:I am saying in Visual Studio 2015

    Leave a Reply

    Your email address will not be published. Required fields are marked *