3

I understand that wrapping an IDbConnection object in a using block ensures that Dispose will get called and the resources it is using will get freed. That being said do I also need to wrap IDbCommand and IDataReader in using blocks as well, or is just wrapping the connection object sufficient. Thanks.

jfin3204
  • 699
  • 6
  • 18
  • It depends on the actual application you are designing. In my work, I need a persistent connection so I don't wrap the connection object in using statements, instead I wrap all the command and readers inside using statements and try/catch blocks, making sure that the finally of every try/catch closes the connection. That way the connection is persistent...but stays closed when not in use. – Nevyn Jan 29 '14 at 17:11

2 Answers2

2

There are a number of easy ways to work out the answer to this for any given object without consulting the documentation:

  1. If you wrap it in a using block and it's not IDisposable, you'll get a syntax error.
  2. If your class has a .Dispose method (easily checked in Intellisense) then you should wrap it.
  3. If your class implements IDisposable (easily checked through "go to definition" or the new "peek" functionality in VS) you should wrap it.

Alternatively, by way of example, you can see from the MSDN docs that IDbCommand implements IDisposable and therefore should be disposed of with a using block.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
  • Ad 2) `using` matching is based on interface, so method may be there, but if it doesn't implement `IDisposable` you wan't be able to use it in `using` statement. And `IDisposable.Dispose` can be implemented explicitely and method may not be seen in Intellisense. – MarcinJuraszek Jan 29 '14 at 17:22
  • True (often the method will be `.Close()` or similar), but it's still a reasonable way of checking. Ultimately I'd always check for the interface (#3), but the other methods are occasionally useful. – Dan Puzey Jan 29 '14 at 17:25
1

The best practice is to wrap any scoped IDisposable object in a using block. This is especially true when you are writing code to interact with interfaces, since you have no idea of the details of the underlying implementations; it might matter in some cases.

bmm6o
  • 6,187
  • 3
  • 28
  • 55