C# Form.Close vs Form.Dispose
I am new to C#, and I tried to look at the earlier posts but did not find a good answer.
In a C# Windows Form Application with a single form, is using Form.Close()
better or Form.Dispose()
?
MSDN says that all resources within the object are closed and the form is disposed when a Close is invoked. Inspite of which, I have come across several examples online which follow a Dispose rather than a Close.
Does one have an advantage over the other? Under which scenarios should we prefer one over the other?
Solution 1:
This forum on MSDN tells you.
Form.Close()
sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.If you do a
form1.Show()
orApplication.Run(new Form1())
, Dispose will be called whenClose()
is called.However, if you do
form1.ShowDialog()
to show the form modally, the form will not be disposed, and you'll need to callform1.Dispose()
yourself. I believe this is the only time you should worry about disposing the form yourself.
Solution 2:
As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.
Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.
In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.