CSharpFeeds - All your C# feeds in one place.

Sponsors

Thursday, January 24, 2008

Chaining the C# ?? Operator

by Rick Strahl via Rick Strahl's Web Log on 1/24/2008 2:12:27 AM

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"] ??
                 string.Empty;

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 <g>...

Posted in CSharp  
kick it on DotNetKicks.com

email it!bookmark it!digg it!

Original Post: Chaining the C# ?? Operator

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us