score:5

Accepted answer

FirstOrDefault provides two logical paths to handle whether there is a data result or there is not. Hence its handling is only local to the scope which it is called in. First provides a method to jump out of the local scope via an exception.

Design WHY

First only returns data for the current scope but gives the ability to handle any unusual or unforseen circumstance of no data and will handle that as an application type error via an Exception. That exception can be handled by a centralized controller outside of the current scope.

Hence it depends on how one wants to handle the lack of data and whether to handle it locally or outside of the local scope and to what degree the no data situation should be processed.

why Microsoft thought there should be two different methods for this?

Flexibility for the programmer to code for different situations as needs dictate.

score:9

First throws an exception if the sequence is empty. This is the only difference.

First has a built-in assertion that the sequence is not empty. That is it's purpose. Sometimes you know that the sequence cannot be empty. For example if you look up a customer in database A and it exists you know it will exist in database B as well. If it ever does not exist in B this would be a bug.

In case of a bug you want a loud bang to alert you of that. That's why assertions are often useful in production code. You certainly do not want to carry on executing with bad data. This makes finding the origin of bug harder, or might even hide the bug completely.

The whole point of First is that it is often super useful to have this built-in assertion.

The same is true for Single and SingleOrDefault. These assert that the sequence can never have more than one element. It turns out that this is often what you want in real-world code.

FirstOrDefault also allows you to handle the case where the sequence is empty whereas First does not (catching the exception would be a misuse of exceptions).

Also, First documents your knowledge about the sequence length so that this fact is obvious to anyone who reads the code.


Related Articles