5/29/2011

What is C Sharp Using statement

The Using statement in C# allows you to define the scope of an object lifetime, when the end of the using satament is reached  the object Dispose() will be called immediatly.

using (SqlConnection conn = new SqlConnection(connString))
{
     SqlCommand cmd = conn.CreateCommand();
     cmd.CommandText = "SELECT * FROM Customers";
     conn.Open();
     using (SqlDataReader dr = cmd.ExecuteReader()) {
          while (dr.Read())
          // Do Something...
     }
}

This is extremly useful when we need to release a resourece intensive object, like database connection object or a transaction scope                 
                                                                          read more

No comments:

Post a Comment