Alcance variable y la declaración 'using' en .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()) en lugar de using (_dataAccess = new MyDataAccessClass()))?

preguntado el 09 de enero de 11 a las 12:01

since the object will be disposed once it exits the using block, I see no benefit of having a variable/reference to the object after that. So (using var x = ... para mi. -

3 Respuestas

Desde 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.

Respondido el 09 de enero de 11 a las 15:01

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.

Respondido el 09 de enero de 11 a las 15:01

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

Respondido el 09 de enero de 11 a las 15:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.