Command Line Parameters

The following examples show two different approaches to using the command line arguments passed to an application.

Example 1

This example demonstrates how to print out the command line arguments.

// cmdline1.cs
// arguments: A B C
using System;

public class CommandLine
{
public static void Main(string[] args)
{
// The Length property is used to obtain the length of the array.
// Notice that Length is a read-only property:
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
for(int i = 0; i <>

Output

Run the program using some arguments like this: cmdline1 A B C.

The output will be:

Number of command line parameters = 3
Arg[0] = [A]
Arg[1] = [B]
Arg[2] = [C]

Example 2

Another approach to iterating over the array is to use the foreach statement as shown in this example. The foreach statement can be used to iterate over an array or over a .NET Framework collection class. It provides a simple way to iterate over collections.

// cmdline2.cs
// arguments: John Paul Mary
using System;

public class CommandLine2
{
public static void Main(string[] args)
{
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
foreach(string s in args)
{
Console.WriteLine(s);
}
}
}

Output

Run the program using some arguments like this: cmdline2 John Paul Mary.

The output will be:

Number of command line parameters = 3
John
Paul
Mary

 

0 comments: