Reputation: 77
After using the null propagation operator a while, I stumbled upon writing a linq clause for selecting a single item. Is there a reason (performance, best practice) not to use ?.First()?
MyList?.First();
or
MyList.FirstOrDefault();
Upvotes: 2
Views: 2216
Reputation: 292575
It's not a question of performance or best practice ; they just don't do the same thing.
MyList?.First()
will return null if MyList
is null (First()
won't even be called thanks to the null propagation operator), and throw an InvalidOperationException
if it's empty (because calling First()
on an empty list is invalid).
MyList.FirstOrDefault()
will throw an ArgumentNullException
if MyList
is null (because you can't call FirstOrDefault
with null), and return null (or the type's default value if it's a value type) if the list is empty.
To handle both cases (MyList
is null, MyList
is empty), you can do this:
MyList?.FirstOrDefault()
Upvotes: 12
Reputation: 77354
Those two lines simply aren't equivalent.
The first will throw if MyList
contains no elements, but not if it's null.
The second will throw if MyList
is null, but not if it contains no elements.
Upvotes: 2