CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
echo All Done.
At this point, open a Developer Command Prompt (see Chapter 2) and navigate to the folder
containing your executable and new *.bat file. Execute the batch logic by typing its name and pressing
the Enter key. You should find the output shown below, given that your Main() method is returning -1.
Had the Main() method returned 0, you would see the message “This application has succeeded!” print
to the console.
***** My First C# App *****
Hello World!
This application has failed!
return value = -1
All Done.
Again, a vast majority (if not all) of your C# applications will use void as the return value from
Main(), which, as you recall, implicitly returns the error code of zero. To this end, the Main() methods
used in this text (beyond the current example) will indeed return void (and the remaining projects will
certainly not need to make use of batch files to capture return codes).
Processing Command-Line Arguments
Now that you better understand the return value of the Main() method, let’s examine the incoming array
of string data. Assume that you now wish to update your application to process any possible commandline parameters. One way to do so is using a C# for loop. (Note that C#’s iteration constructs will be
examined in some detail near the end of this chapter.)
static int Main(string[] args)
{
...
// Process any incoming args.
for(int i = 0; i < args.Length; i++)
Console.WriteLine("Arg: {0}", args[i]);
Console.ReadLine();
return -1;
}
Here, you are checking to see whether the array of strings contains some number of items using the
Length property of System.Array. As you’ll see in Chapter 4, all C# arrays actually alias the System.Array
class, and therefore, share a common set of members. As you loop over each item in the array, its value is
printed to the console window. Supplying the arguments at the command line is equally simple, as
shown here:
C:\SimpleCSharpApp\bin\Debug>SimpleCSharpApp.exe /arg1 -arg2
***** My First C# App *****
Hello World!
77