"It took me more than a year to finish writing this article – a “hot topic” and I wanted it to be clear, simple and right. Also, I was busy and did not want to publish anything “unfinished”. As usual, your feedback and comments are more than welcome. Thank you in advance)
Recently (February 2011), I had to review some .NET code and came across of some wrong implementations of IDisposable.
After discussing with the developers, there were many reasons for what I found, ranging from:
- Not knowing the difference between a “CLR memory resource”, a “managed resource” and an “unmanaged resource”;
- Not understanding “how and when” resources are “released”;
- Not knowing when to override the “Finalize()” method and what should be released by a finalizer?
Even if the recent publications are becoming better, documentation from Microsoft is not fully clear on this subject. There are still some ambiguous areas about when you should implement a Finalizer (I must admit, since I started to do .NET programming back in 2002 (with .NET 1.1), MSDN documentation has improved a lot, but it took me a lot of time to understand this topic – thanks to the books like the ones from Jeffrey Richter [REF-01], Don Box [REF-02] and Bill Wagner [REF-03]).
I have split this matter into two posts :
- # 1 – What + Why + references (this post)
- #2 – A guide about ‘how to implement it’ + samples
If you already know about the IDisposable pattern and what are the types of resources managed by the .NET CLR (Common Language Runtime – Microsoft implementation of the managed runtime environment on the .NET platform), please go directly to the second post. If you do not know or want to learn more about it, please keep reading.
"In my previous post, I classified the different memory resources available in the .NET CLR and I explained the role of the IDisposable interface as well as the use of the Finalize() method.
In this post, I am going to talk more about the implementation details of IDisposable and Finalize().
For reference, I have split this matter into two posts:
- # 1 – What + Why + references
- #2 – A guide about ‘how to implement it’ + samples (this post)
You should know by now when and why you should implement IDisposable and Finalize() method according to the type of resource(s) your class owns. In order to answer the question “How?” we still do need to look at two more aspects: 1) Inheritance (as in Object-Oriented Programming) & 2) Some remaining considerations.
We all know about I Disposable, but how much do we really know? And are we "doing it right?" When I read through this article, I felt I needed to take a another look at some of my code, just to be sure... That's a good article/series. One that gets you to read it and better yet, take action on what you've read. I've got to go now and...um... err... um... well... :P