There is a difference in disposing Modal and Non-Modal forms. In a training I gave last week I noticed that even experienced developers didn't know that Modal Dialogs don't dispose automatically, Non-Modal do.
 new TestForm().Show();
}
privatevoidbuttonShowModalDialog(objectsender, System.EventArgs e){
 new Form2().ShowDialog();
}
The solution to this problem is very simple by creating the Form instance within a using block. This will dispose the Form when it is closed.
 using(TestForm f =new TestForm()){
   f.ShowDialog();
 }
}
An alternative solution uses a try/finnaly. Personally I prefer the previous, it is easier to read and write.
 TestForm f =null;
 try{
   f =new TestForm();
   f.ShowDialog();
 }finally{
   if(f !=null){
     f.Dispose();
   }
 }
}
The following solution isn't correct. You might think it is, but it isn't. The Dispose will not be executed when an Exception is thrown from within the ShowDialog().
 TestForm f =new TestForm();
 f.ShowDialog();
 f.Dispose();
}
All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.
Blog comments
0 responses