Information Technology Reference
In-Depth Information
Method Main
Every C# program must have one entry point—a method that must be called
Main
.
In the sample code throughout this text, I have used a version of
Main
that takes no param-
eters and returns no value. There are, however, four forms of
Main
that are acceptable as the
entry point to a program. These forms are the following:
static void Main() {…}
static void Main( string[] args) {…}
static int Main() {…}
static int Main( string[] args) {…}
The first two forms don't return a value to the execution environment when the program
terminates. The second two forms return an
int
value. A return value, if one is used, is generally
used to report success or failure of the program, where 0 is generally used to indicate success.
The second and fourth forms allow you to pass actual parameters, also called
arguments
,
from the command line, into the program, when it starts. There can be zero or more of these
command-line arguments, separated by spaces or tabs. Each argument is interpreted by the pro-
gram as a string, but you do not need to enclose them in quotation marks on the command line.
For example, the following program called
CommandLineArgs
accepts command-line argu-
ments and prints out each argument supplied.
class Program
{
static void Main(string[] args)
{
foreach (string s in args)
Console.WriteLine(s);
}
}
The following command line executes program
CommandLineArgs
with five arguments.
CommandLineArgs
Jon Peter Beth Julia Tammi
↑
↑
Executable
Arguments
name