tags:

views:

509

answers:

3

Say I want to open a new form..

TestForm test = new TestForm();

What is the good way to close it? More precisely, is only calling close() ok? Should I use the using() {} so dispose() is called ? And finally, suppose there is a dialog that should have only one instance of a dialog opened, is there a well "known" pattern? I've got different choices such as storing it in a static field, and null-"ing" it when it is closed..

Thanks

+4  A: 

It is good practice to use using whenever the object implements IDisposable. This will work for a Modal dialog only:

using (TestForm test = new TestForm())
{
    ....
}

It's syntactically equivalent to a try{}finally{} block, so even if an exception is thrown inside the curly braces, Dispose() will be called on your object.

Mitch Wheat
This pattern is great except the window will be useless as it will disappear before anything can be done with it, as it the message loop never spins.
Phil Wright
He is referring to when you use the using pattern and are not showing modal, if you just show the form it's a non blocking call so immediately after the call to Show() the end of the using block is hit and the resources are released.. the form is gone.
Quintin Robinson
have edited to reflect this.
Mitch Wheat
A: 

Don't stretch yourself to "using" that much. Close() is good enough unless you're creating and destroying hundreds of forms at once. GC will take care of it eventually.

ssg
not entirely true if the object also uses unmanaged resources
Mitch Wheat
+1  A: 

Well in terms of your single instance dialog (if it's modal you don't have to worry) you can make the constructor private and provide a public static method to access the form.

public class MyForm : Form
{
    protected MyForm()
    {
    }

    protected int MyValue { get; set; }

    public static int GetResult()
    {
        using(MyForm myForm = new MyForm())
        {
            if(myForm.ShowDialog == DialogResult.OK)
                return myForm.MyValue;   
        }
        return -1;
    }
}

That would force calls to by in the form of..

int someValue = MyForm.GetResult();
Quintin Robinson