Why doesn't IEnumerable?.First() work?

1.3k Views Asked by At

When I try to use ?.First() on an enumerable object, it throws the error "sequence contains no elements" when the object contains no items.

I recognise that the solution is to use .FirstOrDefault(), but I don't understand why my original effort doesn't work. Am I misunderstanding something or is it just 'one of those things'?

5

There are 5 best solutions below

1
On BEST ANSWER

An empty sequence is not null, it's an actual object that simply has no items in it. ?. doesn't call the member in question if the expression is null, which it's not, so First is called, and First throws an exception when it is passed an empty sequence.

0
On

Because empty collection is not null.

2
On

First() explicitly throws an exception when the sequence contains no elements. FirstOrDefault() gives null if there are no elements (edit: or rather, it gives a default value, which for reference types is null). What would you want First() to return from an empty sequence?

0
On

The null conditional operator (?) tests for null before performing a member access operation. The empty sequence is not null, it just contains no elements. So when you call First() it rightly fails, because there is no first element.

0
On

According to MSDN documentation:

    int? length = customers?.Length; // null if customers is null   
    Customer first = customers?[0];  // null if customers is null  
    int? count = customers?[0]?.Orders?.Count();  // null if customers, the first         customer, or Orders is null  

Therefore, if your collection is not null, then the runtime will try to return the first element. Since the collection is empty and you didn't use FirstOrDefault, an exception is thrown.

Link: https://msdn.microsoft.com/en-us/library/dn986595.aspx