This post originated from an RSS feed registered with .NET Buzz
by Eric Gunnerson.
Original Post: Disposing, using, and null
Feed Title: Eric Gunnerson's C# Compendium
Feed URL: /msdnerror.htm?aspxerrorpath=/ericgu/Rss.aspx
Feed Description: Eric comments on C#, programming and dotnet in general, and the aerodynamic characteristics of the red-nosed flying squirrel of the Lesser Antilles
I had an interesting discussion a day or so ago on when you should implement IDisposable
on a class. Like many things, it's more complicated when you dig a little. There are
three scenarios that are interesting:
1) A class that wraps an unmanaged resource
2) A class that has fields that implement IDisposable
3) A class where no fields implement IDisposable
The first one is the easy one. Since you are directly responsible for that unmanaged
object, you will need to implement a finalizer (written using destructor syntax in
C#) to do the cleanup. You will also *probably* want to implement IDisposable, so
the user can call Dispose() to clean things up. There's a standard idiom in the docs
for doing this.
In the second case, there is no direct cleanup you need to do, so you shouldn't write
a finalizer (what would it do?). If your users will want to clean up early, you may
want to implement IDisposable and call Dispose() on your fields from your Dispose()
function.
In the third case, you should do either. If you do implement a finalizer, you will
just slow things down.
Another related question is whether setting fields to null will result in quicker
recovery of memory. This was important to do in the VB6 world, but in the .NET world,
it rarely does anything. The only time it would help is if there was a variable that
held a live reference, but wouldn't drop off the stack for a long time. I think I
could construct a loop like that, but I think it's pretty rare.