Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper: Possible null assignment to entity marked with notnull attribute

Tags:

c#

.net

resharper

I get this warning on response.GetResponseStream() How should I handle this?

// Get response  
using (var response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream  
    if (response != null)
    {
        var reader = new StreamReader(response.GetResponseStream());
        var responseString = reader.ReadToEnd();
        return responseString;
    }
}

For clarity based on some answers misinterpreting:

This line is not where the warning is occurring:

using (var response = request.GetResponse() as HttpWebResponse)

This line is where the warning is occurring:

var reader = new StreamReader(response.GetResponseStream());
like image 418
katit Avatar asked Jan 23 '12 21:01

katit


2 Answers

var reader = new StreamReader(response.GetResponseStream());

I suspect StreamReader constructor's parameter has a notnull attribute. Try the following:

var stream = response.GetResponseStream();
if (stream == null)
  // throw an exception
var reader = new StreamReader(stream);
like image 121
Miserable Variable Avatar answered Oct 21 '22 03:10

Miserable Variable


Try shortening your code and wrapping disposable resources in using statements:

using (var response = request.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
    return reader.ReadToEnd();
}

or even further:

using (var client = new WebClient())
{
    return client.DownloadString("http://foo.bar.com/")
}
like image 6
Darin Dimitrov Avatar answered Oct 21 '22 03:10

Darin Dimitrov