Miscellaneous Debris

Avner Kashtan's Frustrations and Exultations
A new conditional assignment operator??
This one may have slipped beneath the radar, with all the new .NET 2.0 and WinFX and other improvements and APIs and language changes. It appears that C# 2.0 adds a new operator to the mix, and I never even knew it was there.

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.

Published Thursday, May 04, 2006 12:40 PM by AvnerK

Filed under: , ,

Comments

# re: A new conditional assignment operator??@ Thursday, May 04, 2006 11:29 AM

Small correction:

Console.WriteLine (a != null ? a : b);

Hugo

# re: A new conditional assignment operator??@ Thursday, May 04, 2006 11:32 AM

*nonchalant whistling*

Of course, that's what I originally wrote. I wouldn't make such a silly mistake, would I? :)

Thanks. Fixed.

Avner Kashtan

# Another pointless operator for C#@ Sunday, June 03, 2007 4:23 AM

I remember discovering C#'s null coalescing operator a while ago. I can't say I use it a lot , but it

Miscellaneous Debris

# Another pointless operator for C#@ Sunday, June 03, 2007 4:23 AM

I remember discovering C#'s null coalescing operator a while ago. I can't say I use it a lot , but it's

Miscellaneous Debris

Leave a Comment

(required) 
(required) 
(optional)
(required)