Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does question mark and dot operator ?. mean in C# 6.0?

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?

like image 225
Arkadiusz Kałkus Avatar asked Feb 05 '15 19:02

Arkadiusz Kałkus


People also ask

What does the question mark operator do in C?

The question mark operator, ?:, is also found in C++. Some people call it the ternary operator because it is the only operator in C++ (and Java) that takes three operands. If you are not familiar with it, it's works like an if-else, but combines operators.

What does '?' Mean in C programming?

Most likely the '?' is the ternary operator. Its grammar is: RESULT = (COND) ? ( STATEMEN IF TRUE) : (STATEMENT IF FALSE) It is a nice shorthand for the typical if-else statement: if (COND) { RESULT = (STATEMENT IF TRUE); } else { RESULT = (STATEMENT IF FALSE);

What does question mark and colon mean in C?

As everyone referred that, It is a way of representing conditional operator if (condition){ true } else { false }

What does a question mark mean in C sharp?

The conditional operator ?: , also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false , as the following example shows: C# Copy. Run.


Video Answer


2 Answers

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 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 null 
like image 189
Jon Skeet Avatar answered Sep 21 '22 00:09

Jon Skeet


It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:

if (Model.Model2 == null   || Model.Model2.Model3 == null   || Model.Model2.Model3.Model4 == null   || Model.Model2.Model3.Model4.Name == null) {   mapped.Name = "N/A" } else {   mapped.Name = Model.Model2.Model3.Model4.Name; } 

It can be written like (same logic as above)

mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A"; 

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

Action<TValue> myAction = null;  if (myAction != null) {   myAction(TValue); } 

It can be simplified to:

myAction?.Invoke(TValue); 

DotNetFiddle Example:

using System;

public class Program {   public static void Main()   {     Action<string> consoleWrite = null;          consoleWrite?.Invoke("Test 1");          consoleWrite = (s) => Console.WriteLine(s);          consoleWrite?.Invoke("Test 2");   } } 

Result:

Test 2

Basically, I have applied ?. operator after Model as well. I am trying to know that whether it can be applied directly to the model or does it only work with the navigation properties?

The ? or null conditional operator operators on the left value, regardless of the type of value. And the compiler doesn't care what the value is on the right. It's simple compiler magic (meaning it does something you can already do, just in a simplified why).

For example

  var a = model?.Value; 

is the same as saying

  var a = model == null ? null : model.Value; 

In the second case the evaluation of checking for null has no associate with the value returned. The null conditional operator basically just always return null if the left value is null.

The type of member (Method, Field, Property, Constructor) .Value is irrelevant.

The reason your DotNetFiddle example doesn't work is because the compiler being use for the .Net 4.7.2 isn't compatible with the c# version that support the null conditional operator. Changing it to .Net 5, works:

https://dotnetfiddle.net/7EWoO5

like image 41
Erik Philips Avatar answered Sep 20 '22 00:09

Erik Philips