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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With