Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to nest usings with IDisposable objects?

Tags:

c#

Do I have to wrap all my IDisposable objects in using(){} statements, even if I'm just passing one to another? For example, in the following method:

public static string ReadResponse(HttpWebResponse response)
{
    string resp = null;
    using (Stream responseStream = response.GetResponseStream())
    {
        using (StreamReader responseReader = new StreamReader(responseStream))
        {
            resp = responseReader.ReadToEnd();
        }
    }
    return resp;
}

Could I consolidate this to just one using like this:

public static string ReadResponse(HttpWebResponse response)
{
    string resp = null;
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        resp = reader.ReadToEnd();
    }
    return resp;
}

Can I count on both the Stream and the StreamReader being disposed? Or do I have to use two using statements?

like image 431
gilly3 Avatar asked Mar 30 '12 19:03

gilly3


1 Answers

Yes, you can, but that's because the StreamReader constructor documentation specifically says: "The StreamReader object calls Dispose on the provided Stream object when StreamReader.Dispose is called."

If it didn't, then you could do something like this to at least clean up the code a bit.

using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseReader = new StreamReader(responseStream))
{
    resp = responseReader.ReadToEnd();
}
like image 105
Servy Avatar answered Nov 16 '22 00:11

Servy