Why this matters
`FirstOrDefault` and `SingleOrDefault` imply that a collection might be empty, leading to unnecessary null checks and potential bugs.
Ensure `First()` or `Single()` is used instead of `FirstOrDefault()` or `SingleOrDefault()` when collections are guaranteed to have elements.
`FirstOrDefault` and `SingleOrDefault` imply that a collection might be empty, leading to unnecessary null checks and potential bugs.
Side-by-side examples engineers can pattern-match during review.
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 notvar items = new List<int> { 1, 2, 3 };
int firstItem = items.First(); // Compliantvar items = new List<int> { 1, 2, 3 };
int firstItem = items.FirstOrDefault(); // Noncompliant, this implies the collection might be empty, when we know it is notvar items = new List<int> { 1, 2, 3 };
int firstItem = items.First(); // CompliantFrom the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.