If you came across some C# code like this with nested using statements/resources:
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var reader = new BinaryReader(responseStream))
{
// do something with reader
}
}
}
Is it safe to replace it with something like this?
using (var reader = new BinaryReader(((HttpWebResponse)request.GetResponse()).GetResponseStream()))
{
// do something with reader
}
The example above is just an example of nested disposable resources, so forgive me if it's not exactly correct usage. I'm curious if when you dispose the outermost resource (the BinaryReader in this case), if it will recursively dispose its children for you, or if you need to explicitly dispose each "layer" with separate using statements? E.g. if you dispose the BinaryReader, is it supposed to dispose the response stream, which in turn disposes the response? Thinking about that last sentence makes me think you actually do need the separate using statements, because there's no way to guarantee that a wrapper object would dispose of the inner object. Is that right?