C Sharp

Multiple Main Methods

The designers of C# included a mechanism by which you can define more than one class with a Main method. Why would you want to do that? One reason is to place test code in your classes. You can then use the /main:< className > switch with the C# compiler to specify which class's Main method is to be used. Here's an example in which I have two classes containing Main methods: -

using System;
class Main1
{
    public static void Main()
    {
        Console.WriteLine("Main1");
    }
}
class Main2
{
    public static void Main()
    {
        Console.WriteLine("Main2");
    }
}

To compile this application such that the Main1.Main method is used as the application's entry point, you'd use this switch: -

csc MultipleMain.cs /main:Main1

Changing the switch to /main:Main2 would then use the Main2.Main method.

Obviously, because C# is case-sensitive, you must be careful to use the correct case of the class in the switch as well. In addition, attempting to compile an application consisting of multiple classes with defined Main methods and not specifying the /main switch will result in a compiler error.

by BrainBellupdated
Advertisement: