Search code examples
c#design-patternsstreamusingstreamreader

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()

Solution

  • 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"];
    }