Closing a form during a constructor

Is it possible to close a form while the constructor is executing (or simply to stop it showing at this stage)?

I have the following code:

public partial class MyForm : Form
{        
    public MyForm()
    {
        if (MyFunc())
        {
            this.Close();
        }
    }
}

Which throws an ObjectDisposedException in Main(), here:

    static void Main()
    {            
        ...

        // Following line errors
        Application.Run(new MyForm());
    }

I’ve tried checking the result of MyForm like this:

static void Main()
{            
    ...

    MyForm frm = new MyForm();
    if (frm != null)
    {
        // Following line errors
        Application.Run(frm);
    }
}

But that doesn’t seem to help. Can anyone tell me a way around this, please? Maybe a way to check the form to see if it still exists?


Calling Close from the constructor of the Form is not possible, as it will call Dispose on a Form that has not yet been created. To close the Form after construction, assign an anonymous event handler to the Load event that closes your Form before it is displayed for the first time:

public partial class MyForm : Form
{
    public MyForm()
    {
        if (ShouldClose())
        {
            Load += (s, e) => Close();
            return;
        }

        // ...
    }

    // ...
}

The only thing you could do it set a flag to close it in the constructor, and then closing it in the Shown event. Of course, if you're doing that, it makes sense to move the code to determine whether it should be closed there in the first place.


The following works well:

public partial class MyForm : Form
{        
    public MyForm()
    {
        if (MyFunc())
        {
            this.Shown += new EventHandler(MyForm_CloseOnStart);
        }
    }

    private void MyForm_CloseOnStart(object sender, EventArgs e)
    {
        this.Close();
    }
}

When you call Close() on a form, internally it is disposing of the form and releasing any managed resources. When you do this:

Application.Run(new MyForm());

You'll likely get an ObjectDisposedException. What you need to do is set the Form's visibility through a property:

Application.Run(new MyForm() { Visible = false });

Just make sure you remove the call to Close() in the constructor, or even move the property assignment there too.


Can you make MyFunc static? and then do something like:

static void Main() 
{             
    ... 
    if (MyForm.MyFunc())
    {
        Application.Run(new MyForm()); 
    }
} 

this would essentially give you the same control over whether the form is going to be constructed or not?