Given that the keyword "using" should always be used when applicable, I wanted to go with that. The problem is, how do I know which objects I can use USING?
4 Answers
Objects that implement IDisposable
can be used with the using
construct.
You can view the class' documentation, its definition in code, or use the object explorer in Visual Studio to find implemented interfaces.
Also, if you should try to use a type that does not implement IDisposable
in a using
block, the compiler will emit a warning. This means you can always try it if in doubt, if the compiler complains, you should not use using
. However, you should always be aware of which objects you use are IDisposable
and treat them accordingly.
The primary purpose of IDisposable
(though I have seen it used (and mis-used) for other stuff), is to ensure timely deallocation of unmanaged resources. Unmanaged resources, as the term is used here, might be a hardware device handle, files, streams, connections, etc. Anything, you would like to ensure gets disposed as soon as you are finished with the resource, instead of waiting for the GC to kick in.

- 161,458
- 45
- 265
- 341
-
-
You look it up in the documentation (or by using the object explorer to view implemented interfaces). – driis Aug 16 '12 at 14:19
-
@Testifier: Go to that class's signature. For eg. `TextReader` or `BinaryReader`. – Nikhil Agrawal Aug 16 '12 at 14:43
You can use tools like FxCop or CodeRush to identify code where you don't call Dispose
/use using
on objects implementing IDisposable
. They will warn you in this case.
Also, in Visual Studio, you can use the Object Browser to see which types implement IDisposable
.

- 99,095
- 21
- 171
- 219
It is recommended that in most cases Classes implementing IDisposable
should be used within using
blocks.
To see if a class does implement IDisposable
, you can just look at it's definition. Code style analysis tools like FXCop will also alert you if IDiposable
implementations are not disposed correctly.

- 2,468
- 24
- 28
-
1That's not true. Only `IDisposable` objects can be in a using block. It will be a compiler error otherwise. Additionally, there are cases where you will want to dispose of an `IDisposeable` object without using a `using`, so saying you should *always* us a `using` isn't true. – Servy Aug 16 '12 at 14:23
-
2It's also not true that *using* is only useful for unmanaged resources. It is useful anytime you want IDisposable.Dispose() to execute, whether or not an Exception was thrown in the code block. Sometimes you want managed cleanup code to run deterministically. – Eric J. Aug 16 '12 at 14:24
Use it for local instances of all classes that implement IDisposable
. They have a Dispose
method.

- 12,455
- 7
- 45
- 79