Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top