I have a method that returns like this:
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
return reader.ReadToEnd();
Can I combine the three usings like this and have the same level of safety?
using (var reader = new StreamReader(request.GetResponse().GetResponseStream()))
return reader.ReadToEnd();
Or since this is inside a privately scoped function, can I return safely without a using?
return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
The object that contains this method is not IDisposable
. I'm guessing no to both my questions but I am curious on other viewpoints.
For the general case, you can't make this assumption. For your specific case, some consolidation is possible. In particular, disposing the StreamReader will also close the underlying stream, because the documentation for StreamReader.Close()
makes this guarantee:
Closes the StreamReader object and the underlying stream
(Emphasis mine). Therefore, you can skip middle using block from your sample. However, the same guarantee is not made from the Stream to the HttpResponse object, meaning you still want to keep that. So you can do this:
using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
return reader.ReadToEnd();
Additionally, there is one other situation where you can combine stacked using
blocks into a single block. When all of the items managed by the using blocks are of the same type, you can separate each object with a comma. For example, opening one file for reading and processing the output to another file can be done like this:
using (var infile = new FileStream("infile"), outfile = new FileStream("outfile"))
{
//...
}