Reputation: 2382
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
Upvotes: 1
Views: 1046
Reputation: 300769
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.
Upvotes: 4
Reputation: 82375
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();
Upvotes: 1