I have the following string list:
List<string> Emails = new List<string>();
Trying to see if it has any values, or return an empty string:
string Email = Emails[0] ?? "";
The above code throws an exception:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
But changing the ?? operator to a simple if statement, it works fine:
if (Emails.Count > 0)
Email = Emails[0];
else
Email = "";
What am I missing here?
When the list is empty, should Emails[0] not be null ?
Thanks.
I suggest to change it to:
string Email = Emails.FirstOrDefault() ?? "";
If your list is empty, Emails[0] is not null, it just doesn't exist.
Edit: that works for strings and ref types, if you do have a value type, for example int, you will get default(int) that is 0 as result of FirstOrDefault of empty collection
Emails[0] will try access first item of the list - that is why it throws exception.
You can use "readable" DefaultIfEmpty method for declaring "default" value if collection is empty
string Email = Emails.DefaultIfEmpty("").First();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With