A new conditional assignment operator??

Tags: .NET, C#, CodeSnippets

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.

3 Comments

Comments have been disabled for this content.