- 1 A First C# Program
- 2 Namespaces
- 3 Alternative Forms of the Main() Function
- 4 Making a Statement
- 5 Opening a Text File for Reading and Writing
- 6 Formatting Output
- 7 The string Type
- 8 Local Objects
- 9 Value and Reference Types
- 10 The C# Array
- 11 The new Expression
- 12 Garbage Collection
- 13 Dynamic Arrays: The ArrayList Collection Class
- 14 The Unified Type System
- 15 Jagged Arrays
- 16 The Hashtable Container
- 17 Exception Handling
- 18 A Basic Language Handbook for C#
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:
-t causes the program to turn a trace facility on; by default, tracing is off.
-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().