topgun_ivard topgun_ivard -3 years ago 360
C# Question

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

better or

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?

Answer Source

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() or Application.Run(new Form1()), Dispose will be called when Close() is called.

However, if you do form1.ShowDialog() to show the form modally, the form will not be disposed, and you'll need to call form1.Dispose() yourself. I believe this is the only time you should worry about disposing the form yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download