Thursday, November 6, 2008

The ?? Operator

Today was my first brush with the ?? operator and was pleasantly surprised by what it can do.


string sString1 = null;
string sString2 = "Hi";
string value = "";

// We would normally it this way
value = sString1 != null ? sString1 : sString2;

// Using ?? operator also called as coalescing
value = sString1 ?? sString2;

// In effect, it could be string
// val = a ?? b ?? c
// - The first non-null value is assigned to val
Response.Write(value);


Chaining ?? operator certainly makes it easier to perform a bunch of comparisons. When the ?? operator is chained, it assigns the value of the first non-null value.

1 comments:

Suzanne Seale said...

Hi Narmatha,
It's Suzanne Seale from Homesite.
I figured you've have your new baby by now. I hired someone to do a lightbox in ajax but I don't think he can do it.
Do you have any time or do you know anyone who can help me?
Thanks and congratuations on your new baby. Last I saw you at 8 months pregnant.