Wednesday, 4 June 2014

C# Tutorial-Basics-Command Line Arguments

C# programs can receive command line arguments. They follow the name of the program, when we run it.

using System;

public class CSharpApp 
{
    static void Main(string[] args) 
    {
        for (int i=0; i<args.Length; i++) 
        {
            Console.WriteLine("{0}", args[i]);
        }
    }
}

Command line arguments can be passed to the Main() method.

public static void Main(string[] args) 

This Main() method receives a string array of command line arguments.
for (int i=0; i<args.Length; i++) 
{
    Console.WriteLine("{0}", args[i]);
}

We go through the array of these arguments with a for loop and print them to the console. TheLength property gives the number of elements in the array. Loops and arrays will be described in more detail later.
$ ./commandargs.exe 1 2 3
1
2
3
We provide three numbers as command line arguments and these are printed to the console.

No comments:

Post a Comment