pete the pagan-gerbil
pete the pagan-gerbil

Reputation: 3166

Variable scope and the 'using' statement in .NET

If a variable is at class level (ie, private MyDataAccessClass _dataAccess;, can it be used as part of a using statement within the methods of that class to dispose of it correctly?

Is it wise to use this method, or is it better to always declare a new variable with a using statement (ie, using (MyDataAccessClass dataAccess = new MyDataAccessClass()) instead of using (_dataAccess = new MyDataAccessClass()))?

Upvotes: 0

Views: 1825

Answers (3)

David
David

Reputation: 218847

From MSDN:

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

So technically it'll work, in that it will compile and run and perform as designed. But it's probably not a good idea and won't make for very intuitive code.

Upvotes: 3

Kurru
Kurru

Reputation: 14331

When using "using" inside a method, only if the object is initialised inside the using statement will the object be disposed when the using block closes. Since your object is defined outside of the using block, I don't believe it would automatically be disposed though it should be "closed" since there would still be a reference to it throughout the rest of the program

Upvotes: 0

Otávio Décio
Otávio Décio

Reputation: 74270

I don't think it matters, but I would use a local variable instead of a class level variable simply because it reduces coupling with other class methods.

Upvotes: 2

Related Questions