views:

255

answers:

4

Can Visual Studio 2008 be configured to give me a warning when I forget to dispose an object that implements IDisposable?

+1  A: 

I don't think it can be done at compile time.

however, it can be done at runtime.
I have created an abstract class 'Disposable' (which implements IDisposable, and implements the Disposable pattern). In the finalizer, I issue an Assert when the finalizer is called, and the object has not been disposed.

I've based this on an article of Ian Griffiths:

http://www.interact-sw.co.uk/iangblog/2004/04/26/yetmoretimedlocking

Frederik Gheysels
I would argue against having a base class for handling disposal. Since .NET is single-inheritance, this locks you in to a very strict inheritance chain that requires your DisposeBase to be at the top.
Rex M
besides that you could just use "System.ComponentModel.Component"
Matthew Whited
A: 

I'm not sure if you're using C# or VB, but in C#, the "best practice" way to handle objects of type IDisposable is to place the code in a using block.

"The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources." - MSDN Link

HTH,

-Dan

DanM
This doesn't in any way answer the question.
Joe White
Can Visual Studio 2008 be configured to give me a warning if I create an object that implements IDisposable, and then forget to enclose it within a using block?
ChrisW
+3  A: 

Visual Studio, by itself does not have this feature, but with CodeRush you can have design time warnings and refactorings to insert using blocks where needed.

Scott Weinstein
ReSharper will do this as well.
John Saunders
CodeRush Xpress is even available FOR FREE: http://www.devexpress.com/Products/Visual_Studio_Add-in/CodeRushX/
marc_s
FxCop and Genderme will do this as well (both free)
Paco
+2  A: 

If you turn on FxCop Design rules it will tell you when you don't implement IDisposable and you have members which implement IDisposable, like this:

class Program
{
    private DataTable NotDisposed;

    public Program()
    {
        NotDisposed = new DataTable();
    }
    static void Main()
    {
    }
}
David Silva Smith
FxCop is great for this kind of stuff. 'course it would be nice if visual studio actually warned you if you made a mistake using (or implementing IDisposable), but heck.
Eamon Nerbonne