Possible NullreferenceException

Resharper shows the warning "Possible Warning System.NullReferenceException". However, I do not see how I can get it.

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 warning does not display a warning:

Request.Cookies[0];//Index instead of name

Edit: updated code.

+3
source share
3 answers

I assume that the checker does not check the value of the string passed to the CookieCollection indexer the same every time. I assume that if you change the structure of 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.

+5
source

. Request Cookies , , .

var placeCookie = Request.Cookies["place"]; 
if (placeCookie != null)
{
    string placeInformation = placeCookie.Value;
}
+3

Error, you do not want Request.Cookies["place"].Value != null , right now you will only set the Information to null place.

0
source

Source: https://habr.com/ru/post/1735435/


All Articles