Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition for ?? operator on null object

Tags:

c#

.net

null

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.

like image 237
Koby Douek Avatar asked Apr 20 '26 04:04

Koby Douek


2 Answers

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

like image 113
Maksim Simkin Avatar answered Apr 21 '26 18:04

Maksim Simkin


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();
like image 33
Fabio Avatar answered Apr 21 '26 18:04

Fabio