Reputation: 558
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?
Upvotes: 5
Views: 458
Reputation: 195
HttpCookieCollection.Get() can cause a null reference exception when it is not called from HttpResponse. So, ReSharper is technically correct that an exception could occur, although it will not happen in your code example. This so question shows an example where the null refence is possible.
Upvotes: 0
Reputation: 1039248
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.
Upvotes: 2