Posts
1150
Comments
891
Trackbacks
1
Tips & Tricks: Closing Connections with the Using Statement in C#

Here's a tip from Sreekanth Sunku: "The using statement simplifies code for C# developers by automatically generating a try and finally block when the code is compiled. This ensures that the Dispose method is called even if an exception occurs. The following code fragment shows how to use the using statement."

using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
. . .
} // Dispose is automatically called on the conn variable here

One limitation of the using statement is that you can only put a single type in the parentheses. If you want to ensure that Dispose is called on additional resources, you must nest the using statements as shown in the following example.

using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("CustomerRead");

conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine(dr.GetString(0));
}
}

posted on Tuesday, February 15, 2005 8:40 PM Print
Comments
No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 7 and 8 and type the answer here: