I have a section of code in my project where I an wrapping a Using Block Inside of Another Using Block, I am wondering is this a good practice or just overkill (Please note I understand that this is a very simplistic snippet of code, it was used for illustration purposes only):
protected void Submit_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
cn.Open();
string cmdStr = "SELECT COUNT(*) FROM REGISTRATION WHERE UserName ='" + this.TextBoxUN.Text + "' ";
using (SqlCommand selectUser = new SqlCommand(cmdStr, cn))
{
int temp = Convert.ToInt32(selectUser.ExecuteScalar().ToString());
if (temp == 0)
{
string insCmd = "Insert INTO REGISTRATION (UserName, Password, EmailAddress, FullName, Country) VALUES (@UserName, @Password, @EmailAddress, @FullName, @Country)";
using (SqlCommand insertUser = new SqlCommand(insCmd, cn))
{
try
{
insertUser.Parameters.AddWithValue("@UserName", this.TextBoxUN.Text);
insertUser.Parameters.AddWithValue("@Password", this.TextBoxPass.Text);
insertUser.Parameters.AddWithValue("@EmailAddress", this.TextBoxEA.Text);
insertUser.Parameters.AddWithValue("@FullName", this.TextBoxFN.Text);
insertUser.Parameters.AddWithValue("@Country", this.DropDownListCountry.SelectedItem.ToString());
insertUser.ExecuteNonQuery();
Response.Redirect("~/Login.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
else
{
Response.Write("User already Exists in Database");
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Yes. Good practice. Dispose of stuff in the smallest scope possible, otherwise you're leaving it to GC to do quite some time later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With