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?
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?
:This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
and now it has been made much easier with just:
I strongly recommend you to read it here:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
It can be written like (same logic as above)
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
It can be simplified to:
DotNetFiddle Example:
using System;
Result: