Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# "using" blocks

I've got something like the code below...someone here mentioned that the WebClient, Stream, and StreamReader objects could all benefit from using blocks. Two easy questions:

1: How would this little snippet look with using blocks? I've no problem with doing my own research so resource links are fine but it'd be quicker and easier to just see an example and I'll understand it from that.

2: I'd like to get in the habit of good coding standards, would help if I knew a little about the reasons why using blocks are better...is it just so you don't have to worry about closing or are there more 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()
like image 397
J Benjamin Avatar asked Jan 21 '11 16:01

J Benjamin


2 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"];
}
like image 85
Darin Dimitrov Avatar answered Sep 23 '22 10:09

Darin Dimitrov


using (WebClient client = new WebClient())
{
    // do work
}

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

From MSDN: using Statement (C# Reference)


As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.


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

like image 20
hunter Avatar answered Sep 24 '22 10:09

hunter