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);
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years 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 ( and is also the creator of GeekZilla.


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.

25/Aug/2006 10:20 AM

Add Comment


Your comment has been received and will be shown once it passes moderation.