3
Reply

What are the Two use of an Using Statement in c#?

Manish Rohilla

Manish Rohilla

10y
1.3k
0
Reply

    1)for name space inclusion 2) for code clean up.

    I wish to talk more about the Using Clause. You can Use Using with all the objects that Implements IDisposable Interface, SO when you get out of the Scope of 'Using' , It Disposes the Object and it should not be further Used. This is a best known practice to do so :)

    • To Import a Namespace. Example Using System.Data;
    • To close the connection in ADO.Net
    string cs = ConfigurationManager.ConnectionStrings["ADO"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("select * from sample", con);
                    con.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    GridView1.DataSource = dr;
                    GridView1.DataBind();
                }

    Here above you can see that , i didn't use con.Close() method. Because i used a Using method above.