views:

306

answers:

3

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.

+2  A: 

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.

Lee
Cheers, it resolved the issue! And it's more readable...
Carra
A: 

err don't you want Request.Cookies["place"].Value != null , right now you will only be setting placeInformation to null.

Hogan
Yes, my mistake.
Carra
+2  A: 

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;
}
ChaosPandion
Indeed, just writing "HttpCookie cookie = Request.Cookies["place"];" works and shows no warnings.
Carra
@Carra - Just a side note, I think using indeed in your day to day vocabulary is indeed awesome.
ChaosPandion
English isn't my native language. I meant to use "Yes,...".
Carra
@Cara - I was not implying that you English was incorrect. I was simply saying that I like the word indeed from some strange reason.
ChaosPandion
Someone down-voted this?
ChaosPandion