Team LiB
Previous Section Next Section

More About the Main Method

In Chapter 1, we introduced the Main method as the initial point of execution for a C# program. We'd now like to go into a little more detail on some features and nuances of the Main method.

Main Method Variants

It turns out that there are actually four variations of the Main method header:

  • The first is the version we introduced in Chapter 1—a parameterless method with a return type of void:

          static void Main()
    
  • The next version returns a result of type int instead:

          static int Main()
    

    Returning an int value is a way to signal to the execution environment (operating system) the status of how the program terminated:

          public class Foo
          {
            static int Main() {
              if (something goes awry) {
                return -1;
              }
              else {
                // All is well!
                return 0;
              }
            }
          }
    

    (A return value of 0 is typically used to indicate that the program executed normally.)

  • Then, we have two forms of Main that take an array of strings as an argument, representing command-line arguments that can be passed in to the Main method when the program is invoked. Note that the name given to this array, typically "args", can in actuality be any valid array name:

    
          static void Main(string[] args)
          static int Main(string[] args)
    

    We'll talk about passing command-line arguments into a C# program in more detail later in this chapter.

Note that none of the four Main method headers includes an access modifier (e.g., public). If we were to include one, the runtime will ignore it. The C# convention is to omit the access modifier from the Main method.

Static Main

Why must the Main method of an application be declared to be static? At the moment that the .NET runtime launches an application by calling its Main method, no objects exist yet, because it's the Main method that will start the process of instantiating our application's objects. Thus, we're faced with a "chicken vs. egg" dilemma: how can we invoke the Main method to initiate object creation if we don't have an initial object to invoke it upon?

As we learned in Chapter 7, a static method is a type of method that can be invoked on a class as a whole, even if we don't have an instance of that class handy. So, before any objects have yet been created, the best option for the designers of C# was to mandate that the Main method be designed as a static method, so that it could be called on the class that serves as the "wrapper" for that method.


Team LiB
Previous Section Next Section