-4

Can someone explain the difference between:

if(object?.Count > 0){
    //code   
}

and:

if(object != null && object.Count > 0){
    //code   
}

Or are they doing the same thing? Thank you.

  • The [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators) describe the semantics pretty well. In particular, no, they are not the same thing in the case where `object` is something complicated, as the null conditional operator only evaluates its target once. – Jeroen Mostert Jul 13 '18 at 16:58
  • Think of `object?` as `if (object == null) return null;` - put it all together and you're effectively checking that `object != null` before attempting to call `.Count` on it. Relevant question [here](https://stackoverflow.com/questions/43074622/question-mark-after-session-variable-reference-what-does-that-mean/43074748#43074748). – trashr0x Jul 13 '18 at 17:05
  • I used to wonder why people answer in comments, but after getting downvoted for trying to help, I now understand. – Dan Chase Jul 13 '18 at 17:17

1 Answers1

1

The question mark is the null-conditional operator (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators). It is shorter and more precise to write if you are using C# 6 or above.

reZach
  • 8,945
  • 12
  • 51
  • 97