The Main
method can use arguments, in which case, it takes one of the following forms:
public static int Main(string[] args) public 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 Parse()
method. For example, the following statement converts the string to a long number by using the Parse()
method on the Int64
class (for more information on System classes, see the Reference section of the NGWS SDK):
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]);
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.
// Command line arguments 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: long num = long.Parse(args[0]); Console.WriteLine("The Factorial of {0} is {1}.", num, Factorial.Fac(num)); return 0; } }
The following are two sample runs of the program assuming that the program name is Factorial.exe
.
Run #1:
Factorial 10 The Factorial of 10 is 3628800.
Run #2:
Factorial 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.