Why does the WinForms developer generate some "inconvenient" code in the delete method?

When you create a form or user control, the WinForms constructor generates a delete method that looks like this:

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

The problem with this code is that it can lead to incorrect behavior if it is ever edited to remove additional objects. I saw .designer.cs files with dispose methods that look like this:

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
            if (_myDisposable != null)
                _myDisposable.Dispose();
            if (_myOtherDisposable != null)
                _myOtherDisposable.Dispose();
        }
        base.Dispose(disposing);
    }

... which is wrong, since removing _myDisposable and _myOtherDisposable should not depend on whether the components are null.

, , , , , , : , ?

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if(components != null)
                components.Dispose();
        }
        base.Dispose(disposing);
    }

, .

+5
4

: , Microsoft. , , , , , Microsoft, , , , , , Objectpose().

, Dispose() .Designer.cs, " ", , .

+4

, , Microsoft "" IDisposable .

. : IDisposable. IDisposable .

: ; IDisposable, - .

, Dispose , , Microsoft .

+3

, , Designer.cs.

( MyForm.cs), . ...

, components == null . Drop 1 Button Label, .a >

I just checked, even on an empty form it is not null. (OK, only for Fx 4+, apparently)

+1
source

Recommended Processing Method Recycling the contained resources in a form is to use the FormClosing or FormClosed events. For the same purpose, UserControl has a Disposed event.

+1
source

All Articles