Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare 2 types inside using statement gives compile error?

I want to use this line of code:

using (ADataContext _dc = new ADataContext(ConnectionString), BDataContext _dc2 = new BrDataContext(ConnectionString)){ // ...}

This gives a compile error:

Cannot use more than one type in a for, using, fixed or declartion statement.

I thought this was possible? MSDN says it is: http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx In the MSDN sample code Font is used, which is class and thereby a reference type as well as my two DataContext classes.

What went wrong here? How does my attempt differ from the MSDN sample?

like image 213
citronas Avatar asked Mar 25 '10 23:03

citronas


People also ask

What is a using statement C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

Where to use using in C#?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.

Does using statement Call dispose?

The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.


3 Answers

MSDN declared instances of two objects of the same type. You're declaring multiple types, hence the error message you received.

Edit: To go all "Eric Lippert" on it, section 8.13 of the language specification 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

The key is that these are resources of a given type, not types, which matches the MSDN example.

like image 50
Anthony Pegram Avatar answered Sep 20 '22 19:09

Anthony Pegram


Do this instead

using (ADataContext _dc = new ADataContext(ConnectionString))
using (BDataContext _dc2 = new BrDataContext(ConnectionString))
{ // ...}
like image 34
Catalin DICU Avatar answered Sep 20 '22 19:09

Catalin DICU


The using resource acquisition statement can be a declaration. A declaration can only declare variables of one type.

You can do:

using (TypeOne t = something, t2 = somethingElse) { ... }
// Note that no type is specified before `t2`. Just like `int a, b`

but you can't

using (TypeOne t = something, TypeTwo t2 = somethingElse) { ... }
like image 25
mmx Avatar answered Sep 16 '22 19:09

mmx