I'm looking at using the ??
operator (null-coalescing operator) in C#. But the documentation at MSDN is limited.
My question: If the left-hand operand is not null, does the right-hand operand ever get evaluated?
As ever, the C# specification is the best place to go for this sort of thing.
From section 7.13 of the C# 5 specification (emphasis mine):
A null coalescing expression of the form
a ?? b
a ?? b
requiresa
to be of a nullable type or reference type. Ifa
is non-null, the result ofa ?? b
a ?? b
isa
; otherwise, the result isb
. The operation evaluatesb
only ifa
is null.
There are more details around when any conversions are performed, and the exact behaviour, but that's the main point given your question. It's also worth noting that the null-coalescing operator is right-associative, so a ?? b ?? c
a ?? b ?? c
a ?? b ?? c
is evaluated as a ?? (b ?? c)
a ?? (b ?? c)
... which means it will only evaluate c
if both a
and b
are null.
Why not test it :)
void Main()
{
var leftOrRight = left ?? right;
}
public bool? left
{
get
{
Console.WriteLine ("Left hit");
return true;
}
}
public bool right
{
get
{
Console.WriteLine ("Right hit");
return true;
}
}
And the answer to the question is no
... The second value doesn't get evaluated
From the specification:
A null coalescing expression of the form a ?? b requires a to be of a nullable type or reference type. If a is non-null, the result of a ?? b is a; otherwise, the result is b. The operation evaluates b only if a is null.
(Emphasis added)
Check this out. If name is not null, console show "MyName". If it's null, console shows "Called" then "Allo"
using System;
public class Program
{
public static void Main()
{
string name = "MyName";
Console.WriteLine(name??test());
}
private static string test()
{
Console.WriteLine("Called");
return "Allo";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.