Using IDisposable to unsubscribe events

Yes, go for it. Although some people think IDisposable is implemented only for unmanaged resources, this is not the case – unmanaged resources just happens to be the biggest win, and most obvious reason to implement it. I think its acquired this idea because people couldn’t think of any other reason to use it. Its not like a finaliser which is a performance problem and not easy for the GC to handle well.

Put any tidy-up code in your dispose method. It’ll be clearer, cleaner and significantly more likely to prevent memory leaks and a damn sight easier to use correctly than trying to remember to un-do your references.

The intention of IDisposable is to make your code work better without you having to do lots of manual work. Use its power in your favour and get over some artificial “design intention” nonsense.

I remember it was difficult enough to persuade Microsoft of the usefulness of deterministic finalisation back when .NET first came out – we won the battle and persuaded them to add it (even if it was only a design pattern at the time), use it!

Leave a Comment