Disposing, using, and null

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()

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.

Comments (5)

  1. Jim Argeropoulos says:

    I think this fits into the third group, but in this case you don’t care that it slows things down.

    I typically implement IDisposable when I want to employ a using statement. Honestly, the two things I miss most from C++ are generics and the ease of creating "stack based" classes. Not only is it harder to do in C# you end up with using statements pollutin your code. Granted it is more explicit, but I don’t see that buys much. Why do I miss stack based classes? Well, they allow me to automate some tasks that require both open and close actions. Always it leads to simpler and safer code.

    I know that generics are comming. I just wish I could see that stack based classes were going to get easier too.

  2. Eric says:

    I agree with you about stack based classes. We tried really hard to come up with a way to make it work in the presence of a GC, but we couldn’t make it work.

  3. anyone says:

    So, what is stack based classes ? Do you mean a class which is using circle or one-way iterational references to other classes.

    Thank you.

  4. cody says:

    Hi Eric,

    Why exactly wasn’t it possible to implement a RAII idiom in C#? Deterministic dtors for structs

    would be possible, wouldn’t it?

  5. MBA says:

    Helpful For MBA Fans.