Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible NullreferenceException

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.

like image 470
Carra Avatar asked Dec 29 '22 00:12

Carra


1 Answers

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.

like image 70
Lee Avatar answered Jan 04 '23 07:01

Lee