Question

What is the best practice for implementing IDisposable on a Winform?

  • I have a dialog which extends System.Windows.Forms.Form
  • The generated designer.cs already contains an implementation of the virtual Dispose(bool) method
  • My form has a field added manually which implements IDisposable

Ideally I would be able to hook into the Dispos(bool) override in the generated code to dispose the manually added IDisposable object. Any recommendations on how to do this properly?

Thanks.

Scott

Was it helpful?

Solution

You can move that Dispose implementation out of the .designer.cs and in your .cs.

OTHER TIPS

But, then your field needs to be a Component (implement the IComponent interface or something similar). Wouldn't that be a little overkill ?

Maybe you can attach an eventhandler to the Disposing event, and dispose your fields in that eventhandler ?

(Or just add them to the Dispose method - I don't think it will be a problem, since afaik, the code in the Dispose method is not regenerated ... Ideally, the Dispose method implementation shouldn't have been in the *.designer.cs class ... ).

I unregister any events in the Dispose method found in the form's designer.cs

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        _frmFind.RaiseFindEvent -= _frmFind_RaiseFindEvent;
        base.Dispose(disposing);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top