Wednesday, July 04, 2007

Everyone knows the using statement. The statement that deals with IDisposable interface for us in a clean to write way. There is however one feature of this statement that is almost never mentioned. The feature I'm talking allows for multiple objects initialization of variables. Usage looks as follows:

using (SqlConnection conn1 = new SqlConnection(), 
    conn2 = new SqlConnection())
{

}

This way, both conn1 and conn2 will be disposed - no need to write 2 nested usings.

There is a note about this feature on MSDN but I've not seen it mentioned anywhere else.

Wednesday, July 04, 2007 6:54:54 PM (Central European Standard Time, UTC+01:00)
It is probably never mentioned because it is just about useless. Normally one uses connections and commands in pairs, but the C# syntax doesn't allow this.
Jonathan
Friday, July 27, 2007 6:32:57 PM (Central European Standard Time, UTC+01:00)
this other syntax is not mentioned a lot either, and is used a lot more

using (SqlConnection conn1 = new SqlConnection())
using (SqlCommand cmd = new SqlCommand("select...", conn1))
{

}
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview