Wednesday, April 09, 2008

Tips from the Frontline: null coalescing operator

I knew about this feature but for some reason thought it was new in .NET 3.5.
It's not, the null coalescing operator has been available since 2.0.

So what is it? It's hard to say but easy to use, so a code example might be easier:

string name = Request.QueryString["name"] ?? "Please Supply a Name";

Basically it allows you assign a value for the not null case and an alternate value for the null case.

This used to be done using the conditional operator:

string name = null != Request.QueryString["name"] ? Request.QueryString["name"] : "Please Supply a name";

Very handy for example when populating C# Model Classes from a DataReader.

1 comment:

http://www.binarysemantics.com/ said...

thank you for nice post