This might seem remediable to more senior .NET developers however I wanted to address a mistake I often see more junior .NET developers make.
In .NET the enumerable extension methods First
and Single
are used to select single elements from a sequence.
First
: literally as the name implies, takes the first element of a sequence and returns it. If the sequence is empty then aInvalidOperationException
will be thrown (if you wish a default to be returned when the sequence is empty then use theFirstOrDefault
method instead).Single
: as likeFirst
, takes the first element of the sequence and returns it however unlikeFirst
assumes the sequence to have only one element. If the sequence is empty or has more than one element then anInvalidOperationException
is thrown (if you wish a default to be returned when the sequence is empty then use theSingleOrDefault
method instead).
When to use which?
First
should be used when you genuinely are expecting a sequence of items and want to take the first one.Single
should be used when you expect the sequence to contain only a single item and want to take it.
Beware using First where you should be using Single
Using First
communicates semantically to the reader of your code that you expect the sequence to have >1 item and you actually want the first item.
If the sequence should only ever contain one item, though it will not cause any exception to be thrown, can be confusing for the reader of the code.
The fact that no exception will be thrown could also potentially mask a much bigger problem in your system (i.e. you are allowing more than one item in the sequence but you intended there to be only one item).
Beware using Single where you should be using First
If you use Single
on a multiple item sequence then a InvalidOperationException
will be thrown.
This is a good thing if you only expected the sequence to be singular at that point! If a sequence can ever contain more than one item then avoid the use of Single
otherwise you may often be getting unwanted exceptions simply because you used the wrong method.
Conclusion
The next time you use First
or Single
consider if you are using the correct method. Especially beware of using First
everywhere even on single item sequences. Doing so causes a loss of semantic meaning in your code to the reader.