You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

The null coalescing operator: ??

This is a new feature of c# 2.0. The null coalescing operator is a short cut for checking if a value is null and if so returning the value of the second operand. Kind of like an IIF. The syntax is as follows:

string newValue = someValue ?? "default"

The first operand someValue must be a nullable type. The above code will set the value of newValue to someValue unless it's null, then it'll set it to "default".

You could also use this inline:

Console.WriteLine("The value is " + (someValue ?? "null"));

Another use:

return (bool)(ViewState["IsPaged"] ?? true);
kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Sunday, 20 August, 2006

Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services. Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.

Comments

Greg said:

Good one, and then using the Nullable Value Type definitions such as

string? newValue

this allows you to coalesce many values like so

string? newValue = a ?? b ?? c ?? d;

Then you will get the first none null value or null. No need for some strange default value.

August 25, 2006 - 10:20 AM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views