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?
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 callbase.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: