Monday 12 November 2007

C# ?? Operator

The ?? operator also termed as null Coalescing operator is one of the latest cool stuff in the .net 2.0. This operator returns the left hand operand if it is not null, or else it returns the right operand.

So using the statemtent in ways like

int y = x ?? -1;

so if the value of integer x is not null, then y is assigned the value of x, or in case if x is null, then y is assigned the value of -1. The point worth noticing is the return value if x is null, is -1, so the system knows that the assignement has not been successful.

I am not aware of a mission critical requirement for this operator, but there have been various examples, wherein the non-nullable data field, has been received as null. For eg. if you are displaying a table with user age, it might be possible, that the user has not entered the date, or date of birth. It might be useful to use this operator to display a message in such cases, instead of displaying a "0" or a random number in the report field.


Powered by ScribeFire.

1 comment:

Anonymous said...

Good stuff!