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?

  • The variable must be IDisposable and initialized. - free_ze
  • 3
    @free_ze, not required to initialize - Grundy
  • @Grundy error CS0210: You must provide an initializer for a fixed or using statement - free_ze
  • @Grundy Otherwise, the scope will not be limited to the block - free_ze

1 answer 1

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() .