Currently
I’ve implemented a simple helper method for HttpWebRequest called GetResponse(url). Currently I’m manually closing the WebResponse and StreamReader after reading the result. I’m then returning said result like so:
// construct the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// get the result
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
// clean up and return the result
reader.Close();
response.Close();
return result;
Proposed
Is it safe to encompass the return within using statements instead of closing them; will this have the same effect as the .Close()es?
// construct the request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// get the result
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
That’s not only safe – it’s safer than the original, in that it will dispose of the objects even if an exception is thrown; a
usingstatement is equivalent to atry/finallystatement.In general, whenever you write a
Close()orDispose()call explicitly, consider whether you could use ausingstatement instead.(Note that you’re not using the encoding from the web response, by the way – you’re always assuming UTF-8. Using
WebClientinstead can make this simpler, if that’s an option.)