Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of using Using's In C#

Tags:

c#

I have been looking at using in C# and I want to know if the following code is equivalent;

using (SqlConnection connection1 = new SqlConnection(), connection2 = new SqlConnection())
{
}

To this code;

using (SqlConnection connection1 = new SqlConnection())
using (SqlConnection connection2 = new SqlConnection())
{
}
like image 813
Lukasz Avatar asked Oct 15 '10 16:10

Lukasz


4 Answers

The C# Spec says,

When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multiple resources of a given type. A using statement of the form

    using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement

is precisely equivalent to a sequence of nested using statements:

    using (ResourceType r1 = e1)
       using (ResourceType r2 = e2)
          ...
             using (ResourceType rN = eN)
                statement
like image 141
SLaks Avatar answered Sep 23 '22 05:09

SLaks


You can of course insert some code between the first and second using, that uses connection1 before connection2 is created.

But you aren't, so as it is there is no difference. They both produce the same IL:

IL_0000:  newobj      System.Data.SqlClient.SqlConnection..ctor
IL_0005:  stloc.0     
IL_0006:  newobj      System.Data.SqlClient.SqlConnection..ctor
IL_000B:  stloc.1     
IL_000C:  leave.s     IL_0018
IL_000E:  ldloc.1     
IL_000F:  brfalse.s   IL_0017
IL_0011:  ldloc.1     
IL_0012:  callvirt    System.IDisposable.Dispose
IL_0017:  endfinally  
IL_0018:  leave.s     IL_0024
IL_001A:  ldloc.0     
IL_001B:  brfalse.s   IL_0023
IL_001D:  ldloc.0     
IL_001E:  callvirt    System.IDisposable.Dispose
IL_0023:  endfinally  
like image 35
Jon Hanna Avatar answered Sep 20 '22 05:09

Jon Hanna


Yes, according to section 8.13 of the C# Language Specification:

When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multiple resources of a given type. A using statement of the form

using (ResourceType r1 = e1, r2 = e2, ..., rN = eN)

statement is precisely equivalent to a sequence of nested using statements:

using (ResourceType r1 = e1)
using (ResourceType r2 = e2)
...
using (ResourceType rN = eN)
    statement

like image 41
casperOne Avatar answered Sep 21 '22 05:09

casperOne


Yes, those two pieces of code are equivalent.

Edit

Just tested this with Reflector. Exact same IL is emitted for the two versions, and Reflector decompiles to the following C#:

using (new SqlConnection())
{
    using (new SqlConnection())
    {
    }
}

That is, for both versions, Dispose will be called on both instances, even if one throws an exception in the constructor.

like image 25
2 revs Avatar answered Sep 20 '22 05:09

2 revs