-5

First off, I already know about ternary statements. However, I recently saw a piece of code like this:

public void DoSomething(Result result)
{
    return result?.Actions?.Utterance;
}

What is the question mark operator used for here?

bubbleking
  • 3,329
  • 3
  • 29
  • 49
William
  • 3,335
  • 9
  • 42
  • 74
  • 3
    Better dupe: https://stackoverflow.com/questions/28352072/what-does-question-mark-and-dot-operator-mean-in-c-sharp-6-0 (which is also the second result when you google for `c# question mark operator`) – aquinas May 30 '17 at 18:40
  • 1
    How is asking what the null conditional operator is a duplicate of asking what the equivalent of the null conditional operator is in javascript? – juharr May 30 '17 at 18:42
  • People would not google on the already answered question. So the answer is: `If a evaluates to null, the result of a?.x or a?[x] is null.` and `If a evaluates to non-null, the result of a?.x or a?[x] is the same as the result of a.x or a[x], respectively.` – not2qubit Nov 26 '20 at 19:41

2 Answers2

0

This is the null conditional operator:

Used to test for null before performing a member access (?.) or index (?[) operation.

You method's code without the use of null conditional operator it could be written as below:

public void DoSomething(Result result)
{
    if(result!=null)
    {
        if(result.Actions!=null)
        {
            return result.Actions.Utterance;
        }
        else
        {
            return null;
        }
    }
    else
    {
        return null;
    }

}
Christos
  • 53,228
  • 8
  • 76
  • 108
-1

This operator is the short form for an null conditional if statement:

public void DoSomething(Result result)
{
    if(result != null){
        if(result.Actions != null){
            return result.Actions.Utterance;
        }
    }
    return null;
}
Bennik2000
  • 1,112
  • 11
  • 25