Export (0) Print
Expand All

Command-Line Arguments

The Main method can use arguments, in which case, it takes one of the following forms:

static int Main(string[] args)
static void Main(string[] args)

The parameter of the Main method is a string array that represents the command-line arguments. Usually you check for the existence of the arguments by testing the Length property, for example:

if (args.Length == 0) 
{
   Console.WriteLine("Please enter a numeric argument."); 
   return 1; 
}

You can also convert the string arguments to numeric types by using the Convert class or the Parse method. For example, the following statement converts the string to a long number by using the Parse method on the Int64 class:

long num = Int64.Parse(args[0]);

It is also possible to use the C# type long, which aliases Int64:

long num = long.Parse(args[0]);

You can also use the Convert class method ToInt64 to do the same thing:

long num = Convert.ToInt64(s);

For more information see Parse Method and Convert Class.

Example

In this example, the program takes one argument at run time, converts the argument to a long number, and calculates the factorial of the number. If no arguments are supplied, the program issues a message that explains the correct usage of the program.

// Factorial_main.cs
// arguments: 3
using System; 
public class Factorial 
{
   public static long Fac(long i)
   {
      return ((i <= 1) ? 1 : (i * Fac(i-1)));
   }
}

class MainClass 
{
   public static int Main(string[] args) 
   {
      // Test if input arguments were supplied:
      if (args.Length == 0)  
      {
         Console.WriteLine("Please enter a numeric argument."); 
         Console.WriteLine("Usage: Factorial <num>"); 
         return 1; 
      }

      // Convert the input arguments to numbers:
      try 
      {
           long num = long.Parse(args[0]); 
           Console.WriteLine("The Factorial of {0} is {1}.", 
                        num, Factorial.Fac(num)); 
           return 0;
      }
      catch (System.FormatException)
      {
         Console.WriteLine("Please enter a numeric argument."); 
         Console.WriteLine("Usage: Factorial <num>"); 
         return 1; 
      }
   }
}

Output

The Factorial of 3 is 6.

The following are two sample runs of the program assuming that the program name is Factorial.exe.

Run #1:

Enter the following command line:
Factorial 10
You get the following result:
The Factorial of 10 is 3628800.

Run #2:

Enter the following command line:
Factorial
You get the following result:
Please enter a numeric argument.
Usage: Factorial <num>

For more examples on using command-line arguments, see the example in Creating and Using C# DLLs.

See Also

Main | Return Values | General Structure of a C# Program | Command Line Parameters Tutorial

Show:
© 2014 Microsoft