C# Tutorial - Dissecting Our First Application - The Main MethodWithin the definition of the class is the method Main. This is the entry point of your program, where the program control starts and ends. It is the initial entry point that the CLR will execute automatically when the program is launched. The Main method must be declared within a class or struct. The IDE places the method within the first class created when a Console or Windows application is created. This class by default is named Program. Console ApplicationsWhen you create a Console application, the default Main method is in the following form: static void Main(string[] args)
{
. . .
}
Notice first that there is no access-modifier, so the method defaults to private. The static keyword indicates that you can invoke Main without first creating an object of the class where Main is declared. Normally a method requires an instance of a class in order to be called, but by using the static keyword, the method exists without an instance of the class. The void keyword means that the method does not return a value. Finally, there is a string array passed into the method. This array is used to read parameters as zero-indexed command line arguments, when running the application from the command line. We will exploit this feature in another application. Windows ApplicationsWhen you create a Windows application, the default Main method is in the following form: static void Main()
{
. . .
}
The only difference here is that, the IDE does not add the string array to be passed into the method. This does not mean that it cannot be added by hand, as windows applications can be run from the command line, just like console applications. If you want to try this for yourself, open up a command prompt in the directory C:\Program Files\Microsoft Office\Office10. Create a new word document in the directory C:\temp called test.doc. Now type winword C:\temp\test.doc in the command prompt and if all has gone accordingly, then Word will open the file test.doc that is located in the directory C:\temp. Main AlternativesThe Main method can appear in one of following four ways: static void Main()
{
. . .
}
static void Main(string[] args)
{
. . .
}
static int Main()
{
. . .
return 0;
}
static int Main(string[] args)
{
. . .
return 0;
}
C# is a case-sensitive language, and therefore Main must be spelled with a capital M. Passing ParametersWhen you run an application from the command line, this array is used to read parameters as zero-indexed command line arguments. Each element of the array contains one argument, for example:
Returning ParametersApplications return the value zero when everything is running normally. However we can use this ability to return a value other than zero for error purposes. If you were to run an application from a batch file, error codes could be returned in this manner and acted upon as needs be.
|