8.12 Using Command-Line Arguments

On many systems, it’s possible to pass arguments from the command line (these are known as command-line arguments) to an app by including a parameter of type string[] (i.e., an array of strings) in the parameter list of Main. By convention, this parameter is named args (Fig. 8.24, line 7). You can execute an app directly from the Command Prompt by changing to the directory containing the app’s .exe file, typing the file’s name (possibly followed by command-line arguments) and pressing Enter. When you do this, the execution environment passes any command-line arguments that appear after the app name to the app’s Main method as strings in the one-dimensional array args. The number of arguments passed from the command line is obtained by accessing the array’s Length property. For example, the command "MyApp a b" passes two command-line arguments to app MyApp. You must enter command-line arguments separated by whitespace, not commas. When the preceding command executes, the Main method entry point receives the two-element array args (i.e., args.Length is 2) in which args[0] contains the string "a" and args[1] contains the string "b". Common uses of command-line arguments include passing options and filenames to apps.

Fig. 8.24 Using command-line arguments to initialize an array.

Alternate View

  1   // Fig. 8.24: InitArray.cs
  2   // Using command-line arguments to initialize an array.
  3   using System;
  4
  5   class InitArray
  6   {
  7      static void Main(string[] args)
  8      {
  9         // check number of command-line arguments
 10         if (args.Length != 3)
 11         {
 12            Console.WriteLine(
 13               "Error: Please re-enter the entire command, including
" +
 14                "an array size, initial value and increment.");
 15         }
 16         else
 17         {
 18            // get array size from first command-line argument
 19            var arrayLength = int.Parse(args[0]);
 20            var array = new int[arrayLength]; // create array
 21
 22            // get initial value and increment from command-line argument
 23            var initialValue = int.Parse(args[1]);
 24            var increment = int.Parse(args[2]);
 25
 26            // calculate value for each array element
 27            for (var counter = 0; counter < array.Length; ++counter)
 28            {
 29               array[counter] = initialValue + increment * counter;
 30            }
 31
 32            Console.WriteLine($"{"Index"}{"Value",8}");
 33
 34            // display array index and value
 35            for (int counter = 0; counter < array.Length; ++counter)
 36            {
 37               Console.WriteLine($"{counter,5}{array[counter],8}");
 38            }
 39         }
 40      }
 41   }

C:UsersPaulDeitelDocumentsexamplesch08fig08_24>InitArray.exe
Error: Please re-enter the entire command, including
an array size, initial value and increment.

C:UsersPaulDeitelDocumentsexamplesch08fig08_24>InitArray.exe 5 0 4
Index    Value
    0        0
    1        4
    2        8
    3       12
    4       16

C:UsersPaulDeitelDocumentsexamplesch08fig08_24>InitArray.exe 10 1 2
Index    Value
    0        1
    1        3
    2        5
    3        7
    4        9
    5       11
    6       13
    7       15
    8       17
    9       19

Figure 8.24 uses three command-line arguments to initialize an array. When the app executes, if args.Length is not 3, the app displays an error message and terminates (lines 10–15). Otherwise, lines 16–39 initialize and display the array based on the values of the command-line arguments.

The command-line arguments become available to Main as strings in args. Line 19 gets args[0]—a string that specifies the array size—and converts it to an int value, which the app uses to create the array in line 20.

Lines 23–24 convert the args[1] and args[2] command-line arguments to int values and store them in initialValue and increment, respectively—as always, these lines could result in exceptions if the user does not enter valid integers. Line 29 calculates the value for each array element.

The first sample execution indicates that the app received an insufficient number of command-line arguments. The second sample execution uses command-line arguments 5, 0 and 4 to specify the size of the array (5), the value of the first element (0) and the increment of each value in the array (4), respectively. The corresponding output indicates that these values create an array containing the integers 0, 4, 8, 12 and 16. The output from the third sample execution illustrates that the command-line arguments 10, 1 and 2 produce an array whose 10 elements are the nonnegative odd integers from 1 to 19.

Specifying Command-Line Arguments in Visual Studio

We ran this example from a Command Prompt window. You also can supply command-line arguments in the IDE. To do so, right click the project’s Properties node in the Solution Explorer, then select Open. Select the Debug tab, then enter the arguments in the text box labeled Command line arguments. When you run the app, the IDE will pass the command-line arguments to the app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset