简体   繁体   中英

If condition for ?? operator on null object

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();
string Email = Emails[0]

That is the problem. ?? only checks if whats on its left is null and acts accordingly.

You seem to have the misconception that an empty list has null stored at index 0 . That is most definitely not the case. These two lists are semantically very different:

var emptyList = new List<string>();
var someList = new List<string>() { null };

In your code you are trying to access the item at position zero of an empty list. This is an index out of range exception because there is no such item. The exception is thrown before the ?? operator is even evaluated.

Using Emails[0] will throw exception as you access element 0 that is not exist as Maksim suggested Emails.FirstOrDefault() will return null if the list is empty which you check by ?? coalesce operator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM