confused when using "using block" C#

I often use the "using" block to dispose the objects. Today, I using HttpWebRequest to post data, and I feel confused between two method.

Method 1:

var request = (HttpWebRequest)WebRequest.Create("http://www...");
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write(JsonConvert.SerializeObject(content));
}

Method 2:

var request = (HttpWebRequest)WebRequest.Create("http://www...");
using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
{
    writer.Write(JsonConvert.SerializeObject(content));
}

In method 2, all stream and streamwirter in "using" blocks, so certainly it will be dispose. But in method 1, I am not sure stream request.GetRequestStream() will be dispose. Can anyone explain to me? Thanks alot!

Jon Skeet
people
quotationmark

Basically, it depends on two things:

  • Whether the StreamWriter constructor will ever throw an exception when passed a non-null Stream reference - and I don't think it will in this case. (If the stream were read-only, it would... at which point the stream wouldn't be disposed.)
  • Whether StreamWriter.Dispose disposes of the underlying stream - and it does, unless you've called the constructor overload which explicitly allows you to control that

So basically, I believe it's safe in this case... when your using statement disposes of the StreamWriter, that will dispose of the Stream.

As noted in comments, however, using two using statements means you don't need to perform this sort of reasoning.

people

See more on this question at Stackoverflow