Search code examples
c#.netformswinformsdispose

Proper way to dispose a new Form


So in my apps, I tend to create new instances of forms on the fly, then use Form.Show() to display them (non modal).

private void test_click(object sender, EventArgs e)
{
    var form = new myForm();
    form.Show();
}

However, Code Cracker tells me that these forms should be disposed. So, I wrapped them with the "using" statement, but then they close immediately after opening.

using (var form = new myForm())
{
    form.Show();
}

I don't want to use Form.ShowDialog(), because in a few instances I'm opening new windows that only show reports; I don't need them to be modal.


Solution

  • Hmm, "code cracker" appears to be a very appropriate term for that tool, its advice certainly made you write code that breaks your program. Golden Rule is to never trust IDisposable advice from a static code analysis tool, none of them ever have sufficient insight in code execution. They can never figure out which Dispose() call gets the job done.

    What it cannot see is that the Form class already knows how to dispose itself. It is very easy for it to do so, the object becomes unusable when the window closes. When there is no more window then there's no reason to keep using the Form object. A luxury that isn't otherwise very common in .NET but certainly inspired by very smart programmers that worked for Xerox 45 years ago.

    There is only one special rule you have to keep in mind, it does not dispose itself when you use ShowDialog() to display the window. That was intentional, it makes retrieving the dialog results too risky. Using the using statement for a ShowDialog() call is very easy to do, the call does not return until the window is closed.