Tuesday, 4 August 2015

Handling Multiple Main() Methods in C#

Abstract

The C# language standard requires that the Main() method always be the entry point of the program and triggers the program execution, but the class it is in is not specified by the standard. This article will elaborate a little more on this fact and will explain the possibility and issues of having multiple Main() methods, if at all possible, technically.

Normal Program structure

The code below shows a C# Console program code with only one Main() method.




Execute the application.

The program executes and successfully shows the message in the






Now let's add a second Main() into the program.

To do so there are two ways:
  1.  Add a Program2 class to the same Program.cs file
  2.  Add a separate C# class and define a Main() method in that.
Here for demo purposes I will use the #1 approach and a “class Program2” will be added to the same physical Program.cs file.





Build and Observe the behavior

Now it's time to build the code and as soon as you build (Ctrl+Shift+B) two errors will be shown in the Error List window.



The Error description is as follows

Notice the Yellow highlighted text.

Error 1 Program 'c:\Users\vva597\Documents\Visual Studio 2013\Projects\ConsoleApplication\ConsoleApplication\obj\Debug\ConsoleApplication.exe' has more than one entry point defined: 'ConsoleApplication.Program.Main(string[])'. Compile with /main to specify the type that contains the entry point. c:\users\vva597\documents\visual studio 2013\Projects\ConsoleApplication\ConsoleApplication\Program.cs 7 21 ConsoleApplication


The Issue

Since we have added another Main() program the compiler is now confused about which one to use and it will now rely on the developer's decision to assign one specific Main() to the project for executon.

Go to Project  -> Properties -> Aplication Tab -> Startup object.

You will see that both of the Main() method holders (classes) are listed there as shown in the image below.



Set a Startup object and Re-run

As shown in the previous image, select one of the Main() methods and execute the program. You shall see the two separate messages coming from the two different Main() methods as expected.









1 comment: