What is the difference between these two ?
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
without using*
// Get response
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
Usingrequires that the object applied to it implementIDisposable, and will call theDisposemethod ofIDisposablewhen the object goes out of scope of theusingblock (no matter how it leaves that scope… either by execution flowing through normally, or if anExceptionis thrown).The other variant is bad practice… your resources related to
responsewill not be cleaned up.Note that the
StreamReaderis not being cleaned up in either case. You should use an innerusingblock to accomplish that.