Tuesday, October 5, 2010

What is use of “??”.

It's the null-coalescing operator. Essentially it evaluates the left-hand operand, and if the result is null (either a null reference or the null value for a nullable value type) then it evaluates the right operand.

works something like this:

Instead of doing:

int? number = null;
int result = number == null ? 0 : number;

You can now just do:

int result = number ?? 0;

The result of the expression a ?? b is a if that's not null, or b otherwise. b isn't evaluated unless it's needed.

Two nice things:

*

The overall type of the expression is that of the second operand, which is important when you're using nullable value types:

int? maybe = ...;
int definitely = maybe ?? 10;

(Note that you can't use a non-nullable value type as the first operand - it would be pointless.)
*

The associativity rules mean you can chain this really easily. For example:

string address = shippingAddress ?? billingAddress ?? contactAddress;

That will use the first non-null value out of the shipping, billing or contact address.


Note that due to its associativity, you can write:

int? x = E1 ?? E2 ?? E3 ?? E4;

if E1, E2, E3 and E4 are all expressions of type int? - it will start with E1 and progress until it finds a non-null value.

The first operand has to be a nullable type, but e second operand can be non-nullable, in which case the overall expression type is non-nullable. For example, suppose E4 is an expression of type int (but all the rest are still int? then you can make x non-nullable:

int x = E1 ?? E2 ?? E3 ?? E4;

Share This!


1 comment:

Anonymous said...

i have never think of such a operator. thanks for explaining

Powered By Blogger · Designed By Seo Blogger Templates