Search code examples
c#database-connectioninformixusing-statement

C# / Informix: Do I need to explicitly call Close on my DB Connection if it's in a using statement?


Basically, if I'm doing the following:

using (IfxConnection connection = ConnectionManager.GetConnection())
{
    connection.Open();
    ...
    if (connection != null) connection.Close(); //Is this necessary?
}

Note: IfxConnection is an IBM class that inherits from DBConnection.

I know it won't hurt to leave it in there, but I'm at a point where I'm cleaning up and making my code as efficient as possible, so removing anything that's "extra" would be nice. :)


Solution

  • If IBM cleans up and calls Close() in its IfxConnection class on Dispose(), then it is safe to remove the last line.

    According to the docs, yes, they do.

    Basically, you'd have two choices:

    • go with using() or
    • forfeit using() and go for a try{ ... } finally { if (connectionIsOpen) connection.Close()}

    Using both of them is unnecessary.

    I would vote for using using(). (pun intended) ;-)

    Just do not reuse - argh, again ;-) - the connection that is already disposed - but you wouldn't do that, anyway, do you? :-)