I have the following code in my program:
//Dialog Form Class
public int Age;
private void goButtonClick(object sender, EventArgs e)
{
Age = trackBar1.Value;
Close();
}
//Main Form Class
DialogForm df = new DialogForm();
df.ShowDialog();
df.Dispose();
if(df.Age >= 18)
{
//do stuff
}
Surprisingly, I thought I was going to need a way to access df.Age since it would have been disposed by the Close method but surprisingly, I could access this value. I assumed this was some kind of intelligence of the garbage collector so I added df.Dispose() before calling df.Age just to see what will happen, but I could still access it. So I got confused? Why is this happening? When exactly does an item get disposed?
Usually, the answer is “when your code calls
.Dispose()“, which usually means “when it leaves theusingblock”, however some code has additional things that cause it to be disposed. For example, on a winform, if you use theShow()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:or better:
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():