When working with collections that are known to be non-empty, using First or Single is generally preferred over FirstOrDefault or SingleOrDefault.
Why is this an issue?
Using FirstOrDefault or SingleOrDefault on collections that are known to be non-empty is an issue due to:
- Code Clarity and intent: When you use
FirstOrDefaultorSingleOrDefault, it implies that the collection might be empty, which can be misleading if you know it is not. It can be confusing for other developers who read your code, making it harder for them to understand the actual constraints and behavior of the collection. This leads to confusion and harder-to-maintain code. - Error handling: If the developer’s intend is for the collection not to be empty, using
FirstOrDefaultandSingleOrDefaultcan lead to subtle bugs. These methods return a default value (nullfor reference types anddefaultfor value types) when the collection is empty, potentially causing issues likeNullReferenceExceptionlater in the code. In contrast,FirstorSinglewill throw anInvalidOperationExceptionimmediately if the collection is empty, making it easier to detect and address issues early in the development process. - Code coverage: Potentially, having to check if the result is
null, you introduces a condition that cannot be fully tested, impacting the code coverage.
Code examples
Noncompliant code example
Dim Items As New list(Of Integer) From {1, 2, 3}
Dim FirstItem As Integer = Items.FirstOrDefault() ' Noncompliant, this implies the collection might be empty, when we know it is not
Compliant solution
Dim Items As New list(Of Integer) From {1, 2, 3}
Dim FirstItem As Integer = Items.First() ' Compliant
Resources
Documentation
- Microsoft Learn -
Single - Microsoft Learn -
First - Microsoft Learn -
SingleOrDefault - Microsoft Learn -
FirstOrDefault