When working with collections that are known to be non-empty, using First or Single is generally preferred over FirstOrDefault or SingleOrDefault.
Using FirstOrDefault or SingleOrDefault on collections that are known to be non-empty is an issue due to:
FirstOrDefault or SingleOrDefault, 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. FirstOrDefault and
SingleOrDefault can lead to subtle bugs. These methods return a default value (null for reference types and
default for value types) when the collection is empty, potentially causing issues like NullReferenceException later in the
code. In contrast, First or Single will throw an InvalidOperationException immediately if the collection is
empty, making it easier to detect and address issues early in the development process. null, you introduces a condition that cannot be fully tested,
impacting the code coverage.
var items = new List<int> { 1, 2, 3 };
int firstItem = items.FirstOrDefault(); // Noncompliant, this implies the collection might be empty, when we know it is not
var items = new List<int> { 1, 2, 3 };
int firstItem = items.First(); // Compliant
Single First SingleOrDefault FirstOrDefault