0

I have a C# Windows application with ~20 Forms. Every form got its own variables and graphic elements(pen, rectangles, lines....). When user closes a form I am using

this.Dispose();

Is this all that I have to do for handling closing or I need to add something more?

daneg
  • 29
  • 4
  • `Is this all that I have to do for handling closing or I need to add something more?` Short answer - it depends. There _may_ be need for other `Dispose` calls as well - but calling `Dispose` / `Close` on the form is certainly a good start. – mjwills Dec 30 '20 at 12:21

3 Answers3

2

Forms are shown with ShowDialog have to be disposed (with using or calling Dispose manually). This is enough and you have not to do any more.

Forms are shown with Show are disposed automatically (when Close method is executed) by .Net Framework, you should not dispose it manually.

oleksa
  • 3,688
  • 1
  • 29
  • 54
1
using(var frm = new Form1())
   frm.ShowDialog();

Do NOT just call Dispose() outside of a finally block as this can fail when an exception is thrown

Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • You are aware that `using` calls `Dispose` under the covers? – mjwills Dec 30 '20 at 12:19
  • Yes, but calling `Dispose` outside a `finally` is just a no-no – Charlieface Dec 30 '20 at 12:48
  • To be fair, that (it not executing) is also possible even in a `finally` (if an exception is thrown) - but yes, `using` / finally block is the best we have, yes. Thanks for updating your answer - it is clearer now. – mjwills Dec 30 '20 at 12:56
  • @mjwills no that is not possible. A `finally` will always execute unless there is a catastrophic exception (AccessViolation etc, or someone pulling the electric) – Charlieface Dec 30 '20 at 13:27
  • On Windows, sure. :) On Linux, not so much. https://dotnetfiddle.net/qsHFIf https://stackoverflow.com/questions/65069918/net-framework-finally-block-is-not-being-called-when-the-exception-is-not-bein#comment115038679_65069918 – mjwills Dec 30 '20 at 13:28
  • @mjwills What the h*ll? Is that Mono? Is that not a compiler bug? Just saw your link, wow – Charlieface Dec 30 '20 at 13:30
  • Nope, .NET Core on Linux. It isn't a bug. Its documented. :) https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally – mjwills Dec 30 '20 at 13:31
-1

For opening new form; (this code not for Main form)

Form1 frm = new Form1();
frm.ShowDialog();
frm.Dispose();

For closing opened form;

this.Close();