The "Using" Statement in C#

The using statement in the c# language allows us to define an scope for an object lifetime. This statement obtains the resource specified, executes the statements and finally calls the Dispose() method of the object to clean it up.

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...
}
}

When the end of the using statement block is reached, the object Dispose() method will be immediately called. This is extremely useful when we need to release a resource intensive object, like a database connection object or a transaction scope.

You can instance several objects in the same using statement block:

using (SqlConnection conn, SqlConnection conn2, SqlConnection conn3...) { 

     //Do Something... 

}

As a final note, remember that any object instanced in this statement must implement the System.IDisposable interface. Happy coding!

You might also like...

Comments

Xavier Larrea

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“There are only two kinds of languages: the ones people complain about and the ones nobody uses” - Bjarne Stroustrup