1.3. Alternative Forms of the Main() Function

In the rest of this chapter we'll explore the predefined elements of the C# language as we implement a small program called WordCount. WordCount opens a user-specified text file and calculates the number of occurrences of each word within the file. The results are sorted in dictionary order and written to an output file. In addition, the program supports two command-line options:

  1. -t causes the program to turn a trace facility on; by default, tracing is off.

  2. -s causes the program to calculate and report the amount of time it takes to read the file, process the words, and write the results; by default, timings are not reported.

Our first task in Main() is to access the command-line arguments passed in to our program, if any. We do that by using a second form of Main(), which defines a one-parameter function signature:

class EntryPoint
{
      public static void Main( string [] args ) {}
}

args is defined as an array of string elements. args is automatically filled with any command-line arguments specified by the user. For example, if the user invoked our program as follows:

WordCount -s mytext.txt

the first element of args would hold -s and the second element would hold mytext.txt.

In addition, either form of the Main() function may optionally return a value of type int:

public static int Main() {}
public static int Main( string [] args ) {}

The return value is treated as the exit status of the program. By convention, a return value of 0 indicates that the program completed successfully. A nonzero value indicates some form of program failure. A void return type, paradoxically, internally results in a return status of 0; that is, the execution environment always interprets the program as having succeeded. In the next section we look at how we can use this second form of Main().

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

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