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 examples

Noncompliant code example

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

Compliant solution

var items = new List<int> { 1, 2, 3 };

int firstItem = items.First(); // Compliant

Resources

Documentation

Articles & blog posts