Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

Rated
Read 13,278 times

Related Categories

The "Using" Statement in C#

jxlarrea

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!

Comments