Reputation: 17964
Resharper is showing a "Possible System.NullReferenceException" warning. I however can't see how I can get one.
public class PlaceController : PlanningControllerBase
{
[Authorize]
public ActionResult StartStop(int id)
{
if (Request != null && Request.Cookies != null && Request.Cookies["place"] != null)
{
if (Request.Cookies["place"].Value != null)//Possible NullReferenceException?
{
string placeInformation = Request.Cookies["place"].Value;//Possible NullReferenceException?
//...
}
}
}
}
How can this give a NullReference if I check all fields? Using the following doesn't show the warning:
Request.Cookies[0];//Index instead of name
Edit: updated code.
Upvotes: 4
Views: 10248
Reputation: 78242
You don't need to listen to every single warning. The Request
object and the Cookies
object will never be null so this is all you need.
var placeCookie = Request.Cookies["place"];
if (placeCookie != null)
{
string placeInformation = placeCookie.Value;
}
Upvotes: 4
Reputation: 70513
err don't you want Request.Cookies["place"].Value != null
, right now you will only be setting placeInformation to null.
Upvotes: 0
Reputation: 144126
I assume the checker isn't checking the value of the string passed to the CookieCollection indexer is the same each time. I imagine if you restructure the code to:
if (Request != null && Request.Cookies != null)
{
var place = Request.Cookies["place"];
if (place != null && place.Value == null)
{
string placeInformation = place.Value;
}
}
It might work.
Upvotes: 7