Chaining the C# ?? Operator

ASP.Net Add comments

Rick Strahl has a great post on the C# ?? operator and how to chain the functionality to write tigher code.

C# 2.0 has a nice ?? operator that works as a shortcut for:

string value1 = null;

string value2 = "Test1";

string result = value1 != null ? value1 : value2;

which causes result containing Test1 or the second value.

In C# you can shortcut this special null comparison case with the new ??:

string result = value1 ?? value2;

which is a little easier to write. This is probably not news to you, but what’s really useful is that you can chain these operators together so you can do a whole bunch of null comparisons in a single stroke. For example, I frequently look for a few different querystring variables in a page:

string partner = Request.QueryString["GoogleId"] ??
                 Request.QueryString["PartnerId"] ??
                 Request.QueryString["UserKey"] ??

which still yields a valid result for the first non-null querystring or if nothing is found returning “”.

Note that this also works with the longhand syntax in the first example if you use brackets, but more than one level gets pretty unreadable quickly. The ?? syntax on the other is easily readable. This can certainly save you from writing a bunch of nested IF statements to check for multiple conditions.

Reminds me a bit of JavaScript code using || syntax for null checking, and maybe that’s why I just ran into the chaining aspect now

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Login