If you came across some C# code like this with nested using statements/resources:
using (var response = (HttpWebResponse)request.GetResponse())
{
using (
You need the separate using statements.
In your second example, only the BinaryReader
will get disposed, not the objects used to construct it.
In order to see why, look at what the using statement actually does. It takes your second code, and does something equivalent to:
{
var reader = new BinaryReader(((HttpWebResponse)request.GetResponse()).GetResponseStream());
try
{
// do something with reader
}
finally
{
if (reader != null)
((IDisposable)reader).Dispose();
}
}
As you can see, there would never be a Dispose()
call on the Response
or ResponseStream
.