Start me up!

When you create a new Windows Form project, you get a Form1 out of the box.  In that Form’s code behind, you get a constructor with a call to initialize component.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
}

When you hit F5 to run the application, how does the .NET runtime know to launch Form1?  The answer is that Visual Studio pre-builds another module called Program where there is 1 method, static void Main, that looks like this.

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

So how does the .NET runtime know to look for Program.Main to run?  The answer is that the .NET runtime has hard-coded into its logic to look for static void Main() as described here.  That means that you can put static void Main anywhere in your project and the .NET Runtime will find it.*

The reason I bring this up is because I was peer-reviewing a Windows Form project that had removed the Program file/class and stuck static void main in the code behind of Form1 – and static void main called, you guessed it, Form1.  For a second I froze thinking that they created a recursive loop, when I realized that static void Main only gets called once – Form1 never actually uses it.

In any event, a better practice would be to have a separate module (called Program, MyGreatProgram, whatever) to launch the Form(s) and do whatever pre-processing I necessary.

 

 

* Note that you can override this default behavior by using the Startup object property in the project’s property page:

image

By having as (Not Set), the .NET runtimes looks for static void Main.  You can override this with your own class.method.  For example:

public class MyStartupClass
{
    public static void Main()
    {
        Application.Run(new Form1());
    }
}

and then point to it:

image

Note that if you remove all static void main methods in your project, you will get this exception:

Error    1    Program ‘C:\Users\Jamie\Documents\Visual Studio 2010\Projects\Tff.FormStartupExample\Tff.FormStartupExample\obj\x86\Debug\Tff.FormStartupExample.exe’ does not contain a static ‘Main’ method suitable for an entry point    Tff.FormStartupExample

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: