Thursday, June 24, 2004

All you ever wanted to know about the IDisposable and was ashamed to ask

I have some coworkers who are new to the .NET world, and still need to be introduced to the platform best practices. One of the key knowledge that every .NET programmer should have is the IDisposable interface; when to implement it and when to call it. What happens when you fail to do that is one of the points of this article, but for now let's just say that it can lead to difficult to track software bugs, memory and resource leaks.
Before writing this I researched the Web a lot to find a single place that I could point my colleagues in order to learn about IDisposable, but I could not find an article that covers it both fully and deeply, so I decided to start writing.
As I don't have much free time for now, I will post this on my blog one chapter at a time, probably one topic each day, and when it is finished, I'll post this on sites like Code Project as a finished (huge) article.

The topics I intend to cover are (note that this is my initial planned outline, may it changes a little while I write, but you can consider this as a bare minimum):

The beginning
What's IDisposable?
What are the responsibilities of the IDisposable for the class user?
What happens if I don't call Dispose? Why is IDisposable needed?
Isn't .NET garbage-collected?

Calling Dispose
What happens if I call Dispose twice?
What happens if I use an object that had Dispose called?
Where's the correct place to call Dispose?

Implementing IDisposable
What is the correct way of implementing IDisposable?
Don't forget to throw ObjectDisposedException.

C# Support to IDisposable:
What about C# destructors?
The "using" statement.
The "foreach" statement.

Design implications:
Close or Dispose? Why do both exist?
Why did someone choose a private implementation of IDisposable?
Implications for library writers
Should I dispose a whole hierarchy of IDisposable instances or only the root?
Mis"using" C# support for IDisposable.

Useful links for more information

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?