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())
{
}
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
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
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
Yes, those two pieces of code are equivalent.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With