Library code snippets

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!

Comments

  1. 04 May 2006 at 15:44

    Exists a statement similar to with of Visual Basic .NET in C# ?

    Thanks

    antonio

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of The "Using" Statement in C#.

Leave a comment

Sign in or Join us (it's free).

Xavier Larrea

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Want to stay in touch with what's going on? Follow us on twitter!