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"] ??
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.
I'll be at DevIntersection in Vegas this fall giving sessions on ASP.NET Core with Angular and Localization. Thinking of coming? Use discount code STRAHL and save a few bucks. If you do be sure to stop by and say hello!
Other Posts you might also like