3

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?

JJ.
  • 9,580
  • 37
  • 116
  • 189

4 Answers4

1

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.

driis
  • 161,458
  • 45
  • 265
  • 341
1

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.

enter image description here

sloth
  • 99,095
  • 21
  • 171
  • 219
0

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.

Alexander R
  • 2,468
  • 24
  • 28
  • 1
    That'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
  • 2
    It'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
-1

Use it for local instances of all classes that implement IDisposable. They have a Dispose method.

Matthias Meid
  • 12,455
  • 7
  • 45
  • 79