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!
Related articles
Related discussion
-
Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
by virtualking (0 replies)
-
How to optimize mysql subquery performance?
by Jayaram P (0 replies)
-
C# video Editing/rendering
by pkuchaliya (0 replies)
-
How to Fill DataSet with more records (around 1 lakh) in a faster way
by Jayaram P (0 replies)
-
Can't print on the network with MSADESS ??
by anatha1 (2 replies)
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...
Exists a statement similar to with of Visual Basic .NET in C# ?
Thanks
antonio
This thread is for discussions of The "Using" Statement in C#.