During tests of a web application I came across a runtime error cause by the line:![]()
var startUrl = Request.UrlReferrer.AbsoluteUri;
From within the application, the line works fine. However, if you paste the current URL into the address bar and hit Enter, it will cause a NullReferenceException. The obvious solution is to rewrite as
string startUrl = null; if (Request.UrlReferrer != null) startUrl = Request.UrlReferrer.AbsoluteUri;
Suddenly I *knew* I wanted that null-safe dereferencing operator everybody is talking about:
Personally I prefer the ?. notation to -> or ??? I found elsewhere:
var startUrl = Request?.UrlReferrer?.AbsoluteUri;
This answer on SO illustrates a solution that is currently possible, but a bit verbose for my taste:
R NotNull<T, R>(this T src, Func<T, R> f)
where T : class
where R : class
{
return src != null ? f(src) : null;
}
The class constraint on R is not necessary if you replace null with default(R):
R NotNull<T, R>(this T src, Func<T, R> f)
where T : class
{
return src != null ? f(src) : default(R);
}
Advertisement
