How to keep a local variable in scope across a try and catch block

The following code is erroneous, and won't work, because oSqlConnection goes out of scope before you enter the catch block.

try
{
SqlConnection oSqlConnection = new SqlConnection();
oSqlConnection.Open();
}
catch
{
if (oSqlConnection != null) oSqlConnection.Close();
}

Fix for the IssueThe fix is simple - just declare oSqlConnection before entering the try block.

SqlConnection oSqlConnection = null; // Note the assignment to null to avoid error CS0165 - Use of possibly unassigned local variable 'oSqlConnection'.

try
{
oSqlConnection = new SqlConnection();
oSqlConnection.Open();
}
catch
{
if (oSqlConnection != null) oSqlConnection.Close();
}

For this particular example, you could wrap the SqlConnection class in one that implements IDisposable (if it does not already), so that you could then use a using statement instead of extending the scope of the local.

No comments:

Post a Comment