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)
In the question, if
connection.Dispose()is called on anullconnection 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 theconnectionvariable was set tonullbefore thefinallyblock 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 afinallybut also wants to set the connection tonull.Granting the lack of
using(which is suspect, but whatever), I prefer this pattern:This still protects against
nullvalues* in theconnectionobject, and is a closer mimic for what theusingpattern was already doing behind the scenes.Note, however, you're still missing one important feature of a
usingblock, which is protection against something assigningnullto your variable before the block closes.usingblocks 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).