C# Wishlist: Null-Safe Dereferencing

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.