A new conditional assignment operator??
The operator is ??, and it's a conditional non-null operator. Since that doesn't really mean anything, I'll simply and say that the ?? operator returns the left hand operand if it is non-null, otherwise it returns the righthand operand:
string a = null;
string b = "String";
Console.WriteLine (a ?? b); // Will output "String".
This is shorthand for the common pattern we see using the ternary conditional operator, like this:
Console.WriteLine (a != null ? a : b);
which is in turn shorthand for:
if (a != null)
{
Console.WriteLine(a);
}
else
{
Console.WriteLine(b);
}
The ternary conditional is held by many to be a sin against nature and code readability, though I personally find it quite clear and convenient. The non-null conditional is a bit less clear - there's nothing in its syntax to suggest an either/or relation. Perhaps it will clear things up. Perhaps it will lie unused and forgotten . Time will tell.
Note: For some reason, the MSDN library groups the ?? operator with the Assignment operators, rather than the Conditional operators. Strange.
3 Comments
Comments have been disabled for this content.
Hugo said
Small correction:
Console.WriteLine (a != null ? a : b);
Avner Kashtan said
*nonchalant whistling*
Of course, that's what I originally wrote. I wouldn't make such a silly mistake, would I? :)
Thanks. Fixed.
crork said
N1arxy Great, thanks for sharing this article. Keep writing.