daneg
daneg

Reputation: 29

C# dispose - Is it all that I need?

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?

Upvotes: 0

Views: 65

Answers (3)

Charlieface
Charlieface

Reputation: 71263

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

Upvotes: 1

oleksa
oleksa

Reputation: 4017

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.

Upvotes: 2

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

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

For closing opened form;

this.Close();

Upvotes: -1

Related Questions