C # "use" blocks

I have something like the code below ... someone mentioned here that WebClient, Stream and StreamReader objects can benefit from using blocks. Two simple questions:

1: What does this little snippet look like using blocks? I have no problems doing my own research, so the links to the resources are great, but it would be simpler and easier to just see an example, and I will understand this from that.

2: I would like to get used to good coding standards, I would help if I knew a little about the reasons why it is better to use blocks ... is it just that you do not need to worry about closing or are there any other reasons? Thanks!

WebClient client = new WebClient(); Stream stream = client.OpenRead(originGetterURL); StreamReader reader = new StreamReader(stream); JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine()); string encryptionKey = (string)jObject["key"]; string originURL = (string)jObject["origin_url"]; stream.Close() reader.Close() 
+4
source share
9 answers
 using (var client = new WebClient()) using (var stream = client.OpenRead(originGetterURL)) using (var reader = new StreamReader(stream)) { var jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine()); var encryptionKey = (string)jObject["key"]; var originURL = (string)jObject["origin_url"]; } 

or simply:

 using (var client = new WebClient()) { var json = client.DownloadString(originGetterURL); var jObject = Newtonsoft.Json.Linq.JObject.Parse(json); var encryptionKey = (string)jObject["key"]; var originURL = (string)jObject["origin_url"]; } 
+9
source
 using (WebClient client = new WebClient()) { // do work } 

Provides convenient syntax that ensures the correct use of IDisposable objects.

From MSDN: using Statement (link to C #)


Typically, when you use an IDisposable, you must declare it and create it in a using statement. The using statement calls the Dispose method on the object in the correct way, and also calls the object itself, which leaves the scope as soon as Dispose is called. Inside the used block, the object is read-only and cannot be changed or reassigned.


The using statement ensures that Dispose is called even if an exception occurs when you call methods on the object. You can achieve the same result by placing an object inside a try block, and then calling Dispose on the final block; in fact, this is how the using statement is translated by the compiler.

+5
source
 using(WebClient client = new WebClient()) { } 

coincides with

 WebClient client; try { client = new WebClient(); } finally { if(client != null) { client.Dispose(); } } 

Much easier to use with

+4
source

Simple:

Using *using* not a β€œgood practice” per se, a shorter path (syntactic sugar) for placing the objects you should have. Things like files, database connections, and in your case the network.

You would do something like:

 using(WebClient we = new WebClient)) { //do something with 'we' here } 

This is basically just a shortcut to the usual use of the we variable, and then a call to we.Dispose() , which does the cleanup.

Syntax:

 using (<Any class that Implements IDisposable>) { //use the class } 

Other questions you should see:
What is the relationship between the using keyword and the IDisposable interface? using various types in a using statement (C #)

+2
source

using {} blocks, just call Dispose () in the closing bracket - or rather tell the garbage collector that it can handle the object. You would use it like:

 using (WebClient client = new WebClient()) { Stream stream = client.OpenRead(originGetterURL); StreamReader reader = new StreamReader(stream); JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine()); string encryptionKey = (string)jObject["key"]; string originURL = (string)jObject["origin_url"]; stream.Close() reader.Close() } // 'client' instance gets disposed here 
+1
source

Something like that:

 using(WebClient client = new WebClient()) using(Stream stream = client.OpenRead(originGetterURL)) StreamReader reader = new StreamReader(stream) { JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(reader.ReadLine()); string encryptionKey = (string)jObject["key"]; string originURL = (string)jObject["origin_url"]; } 

As for why using blocks are good and better than manually calling Dispose ... image, if any of the code in this using block using exception before you hit the lines where you are closing everything? You are essentially leaking out any unmanaged resource that an IDisposable object manages under the hood. using ensures that Dispose is called correctly, even in the face of an exception (essentially by inserting the appropriate try / finally block).

Whenever possible (i.e. you do not need to maintain the life of any IDisposable by region), you should use using blocks, if not for any other reason, than they reduce the amount of template code that you must write in order so that your own code is safe and correct.

+1
source

@Darin's answer shows the code. The reason they are good is because using blocks causes the compiler to spit out code that will automatically call "Dispose" on the object (so that it immediately releases any resources that it can use) before exiting the block - even if selected exception inside with block

+1
source

using equivalent to try.. finally , so the utility runs even if an exception is thrown inside the block.

+1
source

There are two reasons for using blocks:

  • They look good.
  • Code inside a block can often throw exceptions. So you need to try finally

At the end, a block block is used, for example

 using (Somthing somthing=...) { DoActions(somthing); } 

identical to the following conttruct:

 {Somthing somthing=... try { DoActions(somthing); } finally { somthing.Dispose(); } }//the outer bracket limits the variable 
+1
source

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


All Articles