With C# 6.0 in the VS2015 preview we have a new operator, ?.
, which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
Best Answer
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if
a
isnull
, thena?.PropertyOfA
will evaluate tonull
rather than throwing an exception - it will then compare thatnull
reference withfoo
(using string's==
overload), find they're not equal and execution will go into the body of theif
statement.In other words, it's like this:
... except that
a
is only evaluated once.Note that this can change the type of the expression, too. For example, consider
FileInfo.Length
. That's a property of typelong
, but if you use it with the null conditional operator, you end up with an expression of typelong?
: