views:

46

answers:

1

I have a form that has a member that implements IDisposable but not IComponent. I need to dispose it when the form disposes. Unfortunately the form's dispose is already implemented in the automatically generated portion of the code, and is not partial.

How can I dispose this object?

+2  A: 

Override Form.Dispose(bool) in your form, and dispose of your object there.

In order to understand how this works, you can refer to MSDN's page on Implementing a Dispose Method. The Form class follows this pattern, which allows you to override Dispose(bool) in subclasses. (Just make sure to call base.Dispose(disposing) correctly in your override, as well.)


If you aren't comfortable moving this from the .designer.cs file into your main .cs file, the other option is to subscribe to your own FormClosed event, and dispose of your resources in that event handler. MSDN recommends this approach - from the docs for FormClosed:

You can use this event to perform tasks such as freeing resources used by the form and to save information entered in the form or to update its parent form.

Reed Copsey
Form Designer has already overriden Form.Dispose() for him. Unfortunately it's a generated method (and, as such, you shouldn't add custom code to it).
Justin Niessner
@Justin: You need to move it, if you're using the designer, into your code - it does work, and doesn't get recreated.
Reed Copsey
@Justin: I just added another (potentially better) option, too ;)
Reed Copsey
@Reed - +1 for the second option. I definitely like it better than relying on Designer behavior.
Justin Niessner
@Justin: I probably do too, though I wish MS provided an extensibility point via an override for this directly... I like using the "normal" IDisposable pattern when possible.
Reed Copsey
@Reed - I definitely agree with you there.
Justin Niessner
I went with moving the dispose, which seems to work fine. If it does cause a problem it's an easy enough fix.
C. Ross