Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpCookieCollection.Get(): Possible NullReferenceException

I see the ReSharper warning 'Possible NullReferenceException' on this code on second line:

var cookie = HttpContext.Current.Response.Cookies[CookieName];
cookie.Expires = DateTime.Now.AddDays(-1);

I checked HttpCookieCollection.Get() Method in MSDN and it says 'If the named cookie does not exist, this method creates a new cookie with that name.'. So it looks like NullReferenceException can't happen.

Is it just ReSharper bug or I missed something?

like image 597
Galina Avatar asked Nov 02 '22 22:11

Galina


1 Answers

So it looks like NullReferenceException can't happen.

HttpContext.Current will be null if you execute this code outside of an ASP.NET context, like for example unit test, console or desktop application.

like image 63
Darin Dimitrov Avatar answered Nov 15 '22 04:11

Darin Dimitrov