Using the operator and IDisposable interface

Is it true that the variables declared in the using statement are located together because they are in the scope of the block?

Do I need to do:

using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation()) { using(SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2()) { } } 

or will that be enough and the "bar" is located along with the "foo"?

 using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation()) { SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2(); } 
+4
source share
3 answers

or will that be enough and the "bar" is located along with the "foo"?

No, the panel will not be removed.

Operator

using converted to a try-finally block, so even if an exception occurs, the finally block provides a call to the Dispose method.

After

 using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation()) { SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2(); } 

Translated to

 { SomeIdisposableImplementation foo; try { foo = new SomeIdisposableImplementation(); SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2(); } finally { if (foo != null) foo.Dispose(); } } 

Leave bar inactive.

+11
source

So that both of them are installed using the using statement, you do not need to insert them, but you can write this

 using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation()) { using(SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2()) { } } 

as

 using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation()) using(SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2()) { } 
+4
source

In the second version, the panel will go out of scope, but will not be removed. But you can put both foo and bar in the same command:

 using (SomeIdisposableImplementation foo = new SomeIdisposableImplementation(), SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2()) { // use foo and bar } 

you can also just put the variables in the use command:

 SomeIdisposableImplementation foo = new SomeIdisposableImplementation(); SomeIdisposableImplementation2 bar = new SomeIdisposableImplementation2(); using (foo, bar) { // use foo and bar } 
+1
source

Source: https://habr.com/ru/post/1494086/


All Articles