[Previous] [Contents] [Next]

The Main Method

Every C# application must have a Main method defined as a method in one of its classes. In addition, this method must be defined as public and static. (We'll get into what static means shortly.) It doesn't matter to the C# compiler which class has the Main method defined, nor does the class you choose affect the order of compilation. This is unlike C++ where dependencies must be monitored closely when building an application. The C# compiler is smart enough to go through your source files and locate the Main method on its own. However, this all-important method is the entry point to all C# applications.

Although you can place the Main method in any class, I would recommend creating a class specifically for the purpose of housing the Main method. Here's an example of doing that using our-so far-simple Employee class: -

class Employee
{
    private int employeeId;
}
class AppClass
{
    static public void Main()
    {
        Employee emp = new Employee();
    }
}

As you can see, the example has two classes. This is a common approach to C# programming even in the simplest applications. The first class (Employee) is a problem domain class, and the second class (AppClass) contains the needed entry point (Main) for the application. In this case, the Main method instantiates the Employee object, and, if this were a real application, it would use the Employee object's members.

[Previous] [Contents] [Next]