CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
Arg: /arg1
Arg: -arg2
As an alternative to the standard for loop, you may iterate over an incoming string array using the
C# foreach keyword. Here is some sample usage (but again, you will see specifics of looping constructs
later in this chapter).
// Notice you have no need to check the size of the array when using "foreach".
static int Main(string[] args)
{
...
// Process any incoming args using foreach.
foreach(string arg in args)
Console.WriteLine("Arg: {0}", arg);
}
Console.ReadLine();
return -1;
Finally, you are also able to access command-line arguments using the static GetCommandLineArgs()
method of the System.Environment type. The return value of this method is an array of strings. The first
index identifies the name of the application itself, while the remaining elements in the array contain the
individual command-line arguments. Note that when using this approach, it is no longer necessary to
define Main() as taking a string array as the input parameter, alth ough there is no harm in doing so.
static int Main(string[] args)
{
...
// Get arguments using System.Environment.
string[] theArgs = Environment.GetCommandLineArgs();
foreach(string arg in theArgs)
Console.WriteLine("Arg: {0}", arg);
}
Console.ReadLine();
return -1;
Of course, it is up to you to determine which command-line arguments your program will respond
to (if any) and how they must be formatted (such as with a - or / prefix). Here, we simply passed in a
series of options that were printed directly to the command prompt. Assume, however, you were
creating a new video game and programmed your application to process an option named -godmode. If
the user starts your application with the flag, you know he is, in fact, a cheater and you can take an
appropriate course of action.
Specifying Command-Line Arguments with Visual Studio
In the real world, an end user has the option of supplying command-line arguments when starting a
program. However, during the development cycle, you might wish to specify possible command-line
flags for testing purposes. To do so with Visual Studio, double-click the Properties icon from Solution
Explorer and select the Debug tab on the left side. From there, specify values using the command-line
arguments text box (see Figure 3-1).
78