Corey Ogburn
Corey Ogburn

Reputation: 24717

Details about inheriting IDisposable?

I've been tasked with going through some old code at work to clean it up and I stumbled across a class:

public class XMLLayer : Object, IDisposable

First I find that the explicit Object inheritance is unnecessary, but then I find that the dispose method is rather useless:

public void Dispose()
{
    Dispose();
}

Nowhere is an instance of XMLLayer in a using block, having its Dispose() explicitly called, or being placed in a IDisposable variable (polymorphism).

Am I wrong in assuming that the idea of the Dispose method was to add your own custom cleanup code for the class?

Upvotes: 3

Views: 5648

Answers (4)

Jan-Peter Vos
Jan-Peter Vos

Reputation: 3197

That dispose doesn't seem so much useless as it is dangerous. it will call itself until eventually it kills the application with a StackOverflowException

You are correct that Dispose is for cleanup. But it's mainly for cleanup of unmanaged resources. Those are the resources that that .NET can't even know exists and therefore won't cleanup either

Upvotes: 1

Kev
Kev

Reputation: 119816

To answer your question:

Am I wrong in assuming that the idea of the Dispose method was to add your own custom cleanup code for the class?

See the following question and its accepted answer:

Proper use of the IDisposable interface

Upvotes: 3

Tim Destan
Tim Destan

Reputation: 2028

No you're right. If that Dispose() method were ever called, it would just call itself repeatedly forever anyway, which is a pretty good indication it's never being used.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500735

That method isn't just useless - it'll cause a StackOverflowException and terminate the app if it's ever called (or just hang that thread forever, if the JIT has made used tail recursion).

Is there anything in XMLLayer which looks like it really needs to be disposed? When C# was new, some people decided to always implement IDisposable "just in case". Fortunately that doesn't happen much these days, as far as I can see.

You should implement IDisposable if it are directly or indirectly holds an unmanaged resource - e.g. if there's a field of type Stream.

Upvotes: 1

Related Questions