1

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

Kara
  • 6,115
  • 16
  • 50
  • 57
user38309
  • 2,268
  • 3
  • 21
  • 33

3 Answers3

5

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

Martin Plante
  • 4,553
  • 3
  • 33
  • 45
2

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 ... ).

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
1

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);
    }
Jim Lahman
  • 2,691
  • 2
  • 25
  • 21