Search code examples
c#null-check

What does the "?" do in accessing an element in C#?


I usually use ? to assign an variable and check null later.

But this does not work in the following context:

var value = PlayerGroup?.Players?[0]?.jsonData?.playerSetting?.useChat?.value ?? true;

Expected: value == true if PlayerGroup.Players is null or has no elements in array.

Result: ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

What the ? do expectly in this context?


Solution

  • Players?[0]?

    This does not work in the case that Players is not null, but empty, as you have already seemed to figure out. Players[0] will be out of bounds then. Try using FirstOrDefault if that is what you want to do. (?.FirstOrDefault()?.)