using(var variable) { } Did I understand correctly that this construct creates the scope of (work) variable. And after closing the parenthesis, call Dispose () on the variable?
using(var variable) { } Did I understand correctly that this construct creates the scope of (work) variable. And after closing the parenthesis, call Dispose () on the variable?
Did I understand correctly that this construct creates the scope of (work) variable.
Yes. If a variable is declared (and initialized) in a block, then its scope is limited only by the using block.
It is also possible to use a using block with an already declared and initialized variable. For what this may be needed, see below.
And after closing the parenthesis, call Dispose () on the variable?
Yes. Such a plot:
using (var x = ...) { x.Foo(); } It is converted by the compiler into the following code:
var x = ...; try { x.Foo(); } finally { if (x != null) { ((IDisposable)x).Dispose(); } } Note that initialization is outside the try block.
Accordingly, using already initialized variable in using is a more compact way of writing try/finally with a call to Dispose() .
Source: https://ru.stackoverflow.com/questions/627394/
All Articles