Pete's comments on .NET, politics, humor, and everything else wrong in the world.

3/03/2007

IDisposable and Conservative Politics

There is a saying "You become a Conservative when you've got something to conserve".

In the programming world, it could be said that "You should only implement IDisposable when you've got something to Dispose". Here is an interesting Q/A interchange between a confused C# newsgroup poster, with some very good answers by Barry Kelly:

Q: "A discussion arose recently in a code review about whether or not one should implement IDisposible (and then call it) on an object which has neither unmanaged resources nor managed resources which are resource intensive (db connections, filestreams, etc.)."

A: If a class implements IDisposable, that tells me as a programmer that I *need* to call Dispose() when appropriate. If the class doesn't own other objects which implement IDisposable, and isn't likely to do so, then I would say - don't implement it.

But if you do implement it, implement it properly. Create a protected virtual void Dispose(bool disposing) method, and have your Dispose() implementation call Dispose(true). Then put all your logic in the protected virtual method. That way, descendants can extend the class properly.

Q: "It seems to me that if you do not have such items to explicitly dispose yourself, then it is best to let the Garbage Collector do its work when it determines it is the best time to clean up these objects."

A: Calling Dispose on an object whose class implements IDisposable does not cause it to be collected ahead of time. Dispose() is just a method call, like any other, a programming convention. There's no magic in the CLR relating to Dispose, the only magic is in C# and its 'using' construct - which is essentially a type-dependent macro.

Q: "But, my question is, does it matter? If I have SimpleObject, and I call simpleObject.Dispose() when I'm done with it, is there an associated performance liability over not calling the method?"

A: Possibly, it will cost more, because you're pointlessly calling a method. But the cost will be vanishingly small.

Q: Also, if I write an empty Dispose() method :Is this object removed from the managed heap when I call that method?

A: No. Explicit deallocation is asymptotically more expensive than a copying / compacting GC like .NET's. That is, it would be more expensive if it did remove it.

Q: "Or is it actually cleaned up on Finalization, because it does not"

A: Only objects which implement finalizers are subject to finalization. And objects should only implement finalizers if they need finalization, that is, if they explicitly wrap an unmanaged resource. Typically this means they have a field of type IntPtr, or they descend from CriticalFinalizerObject, they call unmanaged methods via P/Invoke, etc.

If you aren't familiar, the Dispose pattern is defined by the IDisposable interface.

For classes that aren't sealed and need to do resource cleanup, you should follow the Dispose pattern, which has been designed to ensure reliable, predictable cleanup, to prevent temporary resource leaks, and to provide a standard, unambiguous pattern for disposable classes. It also aids derived classes to correctly release base class resources:

// If there are unmanaged resources to release,// they need to be released here.}disposed = true;

// If it is available, make the call to the// base class's Dispose(Boolean) methodbase.Dispose(disposing);}Again, the bottom line: If your class doesn't have resources that it needs to dispose, you do not need to implement IDisposable. This will be the predominant case, so quit worrying about Dispose and go write some good code!

About Me

I am a former Microsoft C# .NET MVP (Most Valuable Professional) for 10 years , author, and UnEducator based in the Orlando Florida area. I write mostly about .NET, formerly for eggheadcafe and currently at my programming blog at peterbromberg.net. I'm an ex-jazz musician and stockbroker who dreams of being a philanthropist and paying less in taxes. I believe in the US Constitution and free-market "Austrian" economic theories. I'm also a "climate realist" and believe in good science, which is never "settled".

As a computer programmer with over 25 years of hands-on experience in designing and developing large-scale enterprise applications, I am an expert at solving business problems.

I'm on Google+ because I enjoy engaging with others. Unlike Facebook or Twitter, the G+ ecosystem makes this much easier.

I'm a long time Mensa member, but I do not believe that possessing a high IQ makes you smart. My favorite quotation is: "Wrong is Right" -- Thelonius Monk.

I tend to be skeptical of everything, and believe that is a healthy way to approach ideas.

Some subjects that I am interested in are: Art, Jazz, Classical, Photography, Politics, Science, Erotica, Psychology,Economics. One of my hobbies is creating digital photocollage with my original photographs and Autodesk Maya software.

Most all of my posts are public, and I only have two circles: Close Friends (I get notifications) and Friends (Everybody else). You graduate to "Close Friends" when you engage with me and I see that we have some things in common. I am very accessible, but get to know me first by interacting with me before you send me a Hangout request.

NOTE: I occasionally make controversial posts or comments in order to stir debate. This rubs some people the wrong way. That's too bad. My comments are my own, and do not represent in any way those of any employer or client, past or present. I encourage civil debate, whether you agree with me or not, but if you engage in ad-hominem personal insults on one of my posts you are gonna get blocked in a New York second.

Excerpts provided by me are pursuant to the Fair Use Doctrine for educational and discussion purposes per Title 17 U.S.C. Section 107, Copyright Law.

Copyright Disclaimer Under Section 107 of the Copyright Act 1976, allowance is made for "fair use" for purposes such as criticism, comment, news reporting, teaching, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational or personal use tips the balance in favor of fair use.