Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()?.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading