Tuesday, September 25, 2007

?? operator (C#)

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. For example:

    int? x = null;

    ...

    // y = x, unless x is null, in which case y = -1.

    int y = x ?? -1;

The ?? operator also works with reference types:

    //message = param, unless param is null

    //in which case message = "No message"

    string message = param ?? "No message" ;

1 comments:

Prakash said...

A useful function in T-SQL is COALESCE, which takes two arguments and returns the first if it is not null and the second if the first is null.

String a = null;
String b = "abc";
String c = a ?? b;

returns "abc".

These can also be chained, so the first non-null argument is returned, so

String a = null;
String b = null;
String c = "abc";
String d = a ?? b ?? c;

returns "abc".

It's a lot easier to read than the alternative:

String d = (a != null ? a : (b != null ? b : c))

From only4gurus