2

I've seen this in some legacy code which generates code analysis warnings:

  Database db = DatabaseFactory.CreateDatabase(strDBCon);
  DbCommand dbCommand = db.GetSqlStringCommand(sb.ToString());

  using (IDataReader dataReader = db.ExecuteReader(dbCommand))
  {
     while (dataReader.Read())
     {
     }
     dataReader.Close();  // <-- this is redundant as close is covered by using's implicit dispose
  }
  dbCommand.Connection.Close();
  dbCommand.Dispose();
  db = null;

I've read here on SO that the dbCommand.Connection property must be closed in addition to disposing of the dbCommand. I would have thought that dbCommand would dispose of any child disposable objects, in this case Connection. If this is not the case, why?

3
  • What if you wanted to use the same connection for several commands? Generally if you're passing in a disposable object to another disposable object you're responsible for the one you're passing in. Commented May 1, 2013 at 10:14
  • Ok, but it doesn't seem clear from the code that the command object holds a reference to an already created connection rather than one it itself has created. In this case if the db and dbCommand variable are wrapped in using, I'm guessing the db dispose would close the connection? Commented May 1, 2013 at 10:23
  • I'm assuming strDBCon is a string, so that means the Database object is creating the connection object, which to me implies that it is Disposable and when disposed it would dispose the connection that it created. Commented May 1, 2013 at 10:26

1 Answer 1

3

Types have a choice in this respect to either take ownership of a thing or just utilise a thing. In your case, and this specifically, all you're doing is passing in an existing instance that you've created and could well be expecting to use again.

If the type was explicitly constructed with an instance of a type passed in, you might expect it to take ownership of that instance, and therefore manage it as part of its disposal pattern, but not in the case of a transient method call.

Sign up to request clarification or add additional context in comments.

1 Comment

ok I understand thanks. Please see my last edit above to George.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.