Closing a null sql connection

791 Views Asked by At

I have a question about closing an opened connection to a database in C#. Let's say we abandon the "using" method and use a try/catch/finally block to open and close the connection.

try 
{
    connection = new SqlConnection();
    connection.Open();
}
catch (Exception ex)
{
    // Do whatever you need with exception
}
finally
{
  1.connection.Dispose();
  2.if (connection != null)
    {
        connection.Dispose();
    }
}

My question here is what exactly happens if only 1) in this code segment occurs. The connection should always be checked for null before disposed(closed), but what if it isn't, and we try to close a connection object that's null? (I'm interested in what happens to the opened connection, can this lead to a leak)

1

There are 1 best solutions below

4
Joel Coehoorn On

In the question, if connection.Dispose() is called on a null connection without the check, you cause a new exception that has not been handled, and everything that goes with that. Additionally, if this was done because the connection variable was set to null before the finally block without ensuring the connection was closed, it is possible to leak that open connection ... though as a practical matter it's rare to see code in the wild that knows to use a finally but also wants to set the connection to null.

Granting the lack of using (which is suspect, but whatever), I prefer this pattern:

finally
{
    if (connection is IDisposable) connection.Dispose();
}

This still protects against null values* in the connection object, and is a closer mimic for what the using pattern was already doing behind the scenes.

Note, however, you're still missing one important feature of a using block, which is protection against something assigning null to your variable before the block closes. using blocks also protect your connection in a separate (hidden) variable, so you're sure you still have a valid reference at the end of the block (this is new in C# 8).

*(For completeness, the author of that linked tweet is the lead on the C# compiler team, so he should know, and he's not being ironic).