Use Block Exclusions

I have the following code:

try{ using (StreamReader reader = new StreamReader(...), Encoding.ASCII)){ // Code that can throw an exception } }catch (Exception error){ // Display error... } 

What will happen to StreamReader if there is an exception in the using block?

Should I add a finally clause where I close the stream?

+4
source share
4 answers

The StreamReader will be automatically deleted by use, as it is essentially a nested try / finally:

 try{ StreamReader reader = new StreamReader(...), Encoding.ASCII); try { // Code that can throw an exception } finally { reader.Dispose(); } } catch (Exception error) { // Display error... } 
+11
source

Should I add a finally clause where I close the stream?

No, internal using() {} (which is essentially an attempt / finally) takes care of the reader.

This code is basically ok.

+3
source

The using block is similar to calling the .Dispose() method at the end. And .Dispose() in StreamReader calls .Close() .

 using (var reader = new StreamReader(...)) { //do work } 

... the same as ...

 var reader = new StreamReader(...); try { //do work } finally { reader.Dispose(); } 
+3
source

StreamReader opens. Your code is good.

+2
source

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


All Articles