Usually, the answer is "when your code calls .Dispose()
", which usually means "when it leaves the using
block", however some code has additional things that cause it to be disposed. For example, on a winform, if you use the Show()
method to display it, then it is disposed when the form is closed.
HOWEVER! For a form shown via ShowDialog()
, this is not done; after all, it is modal, so the expected lifetime is obvious:
using(var df = new DialogForm())
{
df.ShowDialog();
if(df.Age >= 18)
{
//do stuff
}
}
or better:
int age;
using(var df = new DialogForm())
{
df.ShowDialog();
age = df.Age;
}
if(age >= 18)
{
//do stuff
}
You might also want to check the return value of ShowDialog()
to see whether it was cancelled etc.
But to answer your question directly: the form in your question is never properly disposed. The IDisposable.Dispose()
method is never called.
The garbage collector will find it at some point, and will call the finalizer, which will call the inbuilt Dispose(bool)
pattern, but that is an implementation detail of winforms, and is not proper disposal.
See also MSDN for ShowDialog()
:
When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel. Unlike non-modal forms, the Close method is not called by the .NET Framework when the user clicks the close form button of a dialog box or sets the value of the DialogResult property. Instead the form is hidden and can be shown again without creating a new instance of the dialog box. Because a form displayed as a dialog box is hidden instead of closed, you must call the Dispose method of the form when the form is no longer needed by your application.