patterncsharpCritical
What does question mark and dot operator ?. mean in C# 6.0?
Viewed 0 times
anddotmarkdoesmeanoperatorwhatquestion
Problem
With C# 6.0 in the VS2015 preview we have a new operator,
What exactly does it do?
?., 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?
Solution
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
In other words, it's like this:
... except that
Note that this can change the type of the expression, too. For example, consider
"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 is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}... 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 type long, but if you use it with the null conditional operator, you end up with an expression of type long?:FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be nullCode Snippets
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be nullContext
Stack Overflow Q#28352072, score: 791
Revisions (0)
No revisions yet.