IDisposable interface in C #

I studied C # and I read about the IDisposable interface with a single Dispose () method calling it using using syntax. If I use the following:

Class b=new Class(); using(b) { //statements } using (Class o=new Class()) { //statements } 

What happens if I try to use the b and o objects after the curly braces end in both cases?

+4
source share
2 answers

b will still be in scope and not null, but the most well-implemented classes that dispose should throw an exception if you try to use them after they have been called Dispose (which prevents you from using it in the future).

It will be compiled and can still be used - it depends entirely on how it was implemented domestically. However, you should not use it, because its state is not guaranteed and creates confusing code.

o will be unavailable and will not compile.

All using statements do this because the compiler emits some try-catch and calls Dispose on the wrapped object. He does not do anything.

+5
source

if you need an object later, you do not need to use a use block. it is recommended to use it, but in some cases you can use the following structure:

 class b = null; try { b = new class(); /* ... do your stuff ... */ } catch (Exception) { /* handle errors */ throw; } finally { if (b != null) { b.Dispose(); b = null; } } 

thus b will be located at the end of your method, if exists.

you are also allowed to have a use block inside the block used:

 using (Class a=new Class()) { /* you can access a here */ using (Class b=new Class()) { /* you can access a and b here */ } } 
0
source

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


All Articles