Search code examples
c#visual-studionull-conditional-operator

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


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'?


Solution

  • 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.