+21  A: 

FxCop might help (although it didn't spot a test I just fired at it); but yes: you are meant to check. IDisposable is simply such an important part of the system that you need to get into this habit. Using intellisense to look for .D is a good start (though not perfect).

However, it doesn't take long to familiarize yourself with types that need disposal; generally anything involving anything external (connection, file, database), for example.

ReSharper does the job too, offering a "put into using construct" option. It doesn't offer it as an error, though...

Of course, if you are unsure - try using it: the compiler will laugh mockingly at you if you are being paranoid:

using (int i = 5) {}

Error   1 'int': type used in a using statement must be implicitly convertible to 'System.IDisposable'
Marc Gravell
A: 

Like Fxcop (to which they're related), the code analysis tools in VS (if you have one of the higher-up editions) will find these cases too.

Will Dean
Actually, I've just tried both FxCop and the VSTS analysis; neither spotted a missed "using" in a trivial test...
Marc Gravell
A: 

Always try to use the "using" blocks. For most objects, it doesn't make a big difference however I encountered a recent issue where I implemented an ActiveX control in a class and in didn't clean up gracefully unless the Dispose was called correctly. The bottom line is even if it doesn't seem to make much of a difference, try to do it correctly because some time it will make a difference.

Ryan
That's a classic workaround for problems with COM interop / ActiveX interop. It's certainly an argument for tidying up those objects with `using`. It's not necessarily an argument for tidying up **every** object with `using`
MarkJ
I don't know if I would call it a "workaround"; it is more of cleaning up unmanaged resources that may crash or otherwise cause problems. As far as "an argument for tidying up every object" - my opinion is you should always .Dispose of object implementing IDisposable unless there is a very good reason otherwise and the "using" block is typically the easiest mechanism for doing so. It's not really an argument, just my opinion. Others, e.g. Scott Dorman's answer, have made more of an attempt at an argument.
Ryan
+12  A: 

If an object implements the IDisposable interface, then it is for a reason and you are meant to call it and it shouldn't be viewed as optional. The easiest way to do that is to use a using block.

Dispose() is not intended to only be called by an object's finalizer and, in fact, many objects will implement Dispose() but no finalizer (which is perfectly valid).

The whole idea behind the dispose pattern is that you are providing a somewhat deterministic way to release the unmanaged resources maintained by the object (or any object in it's inheritance chain). By not calling Dispose() properly you absolutely can run in to a memory leak (or any number of other issues).

The Dispose() method is not in any way related to a destructor. The closest you get to a destructor in .NET is a finalizer. The using statement doesn't do any deallocation...in fact calling Dispose() doesn't do any deallocation on the managed heap; it only releases unmanaged resources that had been allocated. The managed resources aren't truely deallocated until the GC runs and collects the memory space allocated to that object graph.

The best ways to determine if a class implements IDisposable are:

  • IntelliSense (if it has a Dispose() or a Close() method)
  • MSDN
  • Reflector
  • Compiler (if it doesn't implement IDisposable you get a compiler error)
  • Common sense (if it feels like you should close/release the object after you're done, then you probably should)
  • Semantics (if there is an Open(), there is probably a corresponding Close() that should be called)
  • The compiler. Try placing it in a using statement. If it doesn't implement IDisposable, the compiler will generate an error.

Think of the dispose pattern as being all about scope lifetime management. You want to acquire the resource as last as possible, use as quickly as possibly, and release as soon as possible. The using statement helps to do this by ensuring that a call to Dispose() will be made even if there are exceptions.

Scott Dorman
+1  A: 

@Atario, not only the accepted answer is wrong, your own edit is as well. Imagine the following situation (that actually occurred in one CTP of Visual Studio 2005):

For drawing graphics, you create pens without disposing them. Pens don't require a lot of memory but they use a GDI+ handle internally. If you don't dispose the pen, the GDI+ handle will not be released. If your application isn't memory intensive, quite some time can pass without the GC being called. However, the number of available GDI+ handles is restricted and soon enough, when you try to create a new pen, the operation will fail.

In fact, in Visual Studio 2005 CTP, if you used the application long enough, all fonts would suddenly switch to “System”.

This is precisely why it's not enough to rely on the GC for disposing. The memory usage doesn't necessarily corelate with the number of unmanaged resources that you acquire (and don't release). Therefore, these resoures may be exhausted long before the GC is called.

Additionally, there's of course the whole aspects of side-effects that these resources may have (such as access locks) that prevent other applications from working properly.

Konrad Rudolph
+2  A: 

This is why (IMHO) C++'s RAII is superior to .NET's using statement.

A lot of people said that IDisposable is only for un-managed resources, this is only true depending on how you define "resource". You can have a Read/Write lock implementing IDisposable and then the "resource" is the conceptual access to the code block. You can have an object that changes the cursor to hour-glass in the constructor and back to the previously saved value in IDispose and then the "resource" is the changed cursor. I would say that you use IDisposable when you want deterministic action to take place when leaving the scope no matter how the scope is left, but I have to admit that it's far less catchy than saying "it's for managing un-managed resource management".

See also the question about why there's no RAII in .NET.

Motti
Finalizers are for unmanaged resource management; IDisposable is for *deterministic* resource management. Typically for an unmanaged resource you want both - but it is fine to use IDisposable independently of unmanaged code.
Marc Gravell
You should NOT be using IDisposable to change the cursor or anything else. It is purely for freeing up unmanaged resources. You are "using it off-label", as Eric Lippert says. Read his comments at http://blogs.msdn.com/ericlippert/archive/2009/03/06/locks-and-exceptions-do-not-mix.aspx
GrahamS
In what way is a cursor not an "unmanaged resource"? Every control has one and when you change it you're contending with other people who want it otherwise changed and if it is "leaked" the cursor remains in the wrong state.
Motti
A: 

Unfortunately, neither FxCop or StyleCop seem to warn on this. As other commenters have mentioned, it is usually quite important to make sure to call dispose. If I'm not sure, I always check the Object Browser (Ctrl+Alt+J) to look at the inheritance tree.

Brent Rockwood
A: 

I use using blocks primarily for this scenario:

I'm consuming some external object (usually an IDisposable wrapped COM object in my case). The state of the object itself may cause it to throw an exception or how it affects my code may cause me to throw an exception, and perhaps in many different places. In general, I trust no code outside of my current method to behave itself.

For the sake of argument, lets say I have 11 exit points to my method, 10 of which are inside this using block and 1 after it (which can be typical in some library code I've written).

Since the object is automatically disposed of when exiting the using block, I don't need to have 10 different .Dispose() calls--it just happens. This results in cleaner code, since it is now less cluttered with dispose calls (~10 fewer lines of code in this case).

There is also less risk of introducing IDisposable leak bugs (which can be time consuming to find) by somebody altering the code after me if they forget to call dispose, because it isn't necessary with a using block.

+1  A: 

I don't really have anything to add to the general use of Using blocks but just wanted to add an exception to the rule:

Any object that implements IDisposable apparently should not throw an exception during its Dispose() method. This worked perfectly until WCF (there may be others), and it's now possible that an exception is thrown by a WCF channel during Dispose(). If this happens when it's used in a Using block, this causes issues, and requires the implementation of exception handling. This obviously requires more knowledge of the inner workings, which is why Microsoft now recommends not using WCF channels in Using blocks (sorry could not find link, but plenty other results in Google), even though it implements IDisposable.. Just to make things more complicated!

The Giraffe
+3  A: 

In short, it's not the end of the world if I miss a using. I just wish something would generate at least a warning for it.

The problem here is that you can't always deal with an IDisposable by just wrapping it up in a using block. Sometimes you need the object to hang around for a bit longer. In which case you will have to call its Dispose method explicitly yourself.

A good example of this is where a class uses a private EventWaitHandle (or an AutoResetEvent) to communicate between two threads and you want to Dispose of the WaitHandle once the thread is finished.

So it isn't as simple as some tool just checking that you only create IDisposable objects within a using block.

GrahamS
A: 

According to this link the CodeRush add-in will detect and flag when local IDisposable variables aren't cleaned up, in real-time, as you type.

Could meet you halfway on your quest.

Scott Bilas