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?
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?
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;
}
}
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;
}