Last post Aug 28, 2017 09:55 AM by bobh0526
Aug 28, 2017 09:04 AM|bobh0526|LINK
I have this code in a C# class file:
using (SqlConnection con = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand())
using (SqlDataAdapter sda = new SqlDataAdapter())
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.CommandText = "AC_spGetEmailRedirects";
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
} // using DataSet
} // end using SqlDataAdapter
} // end using SqlCommand
} // end using SqlConnection
} // try
catch (Exception ex)
string str = "Error! An exception occurred. <br /><br /> Message: " + ex.Message;
The con in my finally section has this error:
The name 'con' does not exist in current context.
How do I fix this?
Aug 28, 2017 09:40 AM|PatriceSc|LINK
This is precisely the purpose of the using statement. See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement that
shows the code used behind the scene for "using". So here you just don't need at all the finally block.
Not directly related but showing an exception message to users and returning null to the caller is perhaps not the best strategy :
- more likely the user won't know what to do
- those in charge of monitoring the app won't know about the error
- more likely you'll have other errors later if your code is not explicitely prepared to deal with a null DataTable
My basic approach is to show a generic message and log/warn the IT team about the error.
Aug 28, 2017 09:55 AM|bobh0526|LINK
Thanks for the clarification. I didn't realize that the using meant I didn't need the finally section. I was not showing exception messages to the user. I instead write exceptions to a log file.