Resharper: Possible null assignment to entity marked with notnull attribute

自作多情 提交于 2019-11-29 15:57:41

问题


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());

回答1:


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);



回答2:


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/")
}



回答3:


If the response object is of type HttpWebRequest, then response will always be of type HttpWebResponse. If it's not, then it never will be.

Either you're testing this at the wrong place (why call .GetResponse() if you could be passed another class derived by WebRequest just to throw away the results) or testing unnecessary with no effect.

I'm guessing resharper is worrying about that, despite the test for null below it. I'd go for either a direct cast:

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

Or, considering you aren't using any members of HttpWebResponse that isn't derived from WebResponse, no cast at all:

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


来源:https://stackoverflow.com/questions/8979008/resharper-possible-null-assignment-to-entity-marked-with-notnull-attribute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!