4

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.

Carra
  • 17,808
  • 7
  • 62
  • 75
  • Is there a reason why you want to set the variable `placeInformation` when `Request.Cookies["place"].Value` is null or was that a mistake? – Çağdaş Tekin Mar 04 '10 at 15:35

3 Answers3

7

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
  • 142,018
  • 20
  • 234
  • 287
4

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
  • 77,506
  • 18
  • 119
  • 157
0

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

Hogan
  • 69,564
  • 10
  • 76
  • 117