← back to index

S7130 — First/Single should be used instead of FirstOrDefault/SingleOrDefault on collections that are known to be non-empty

Language: C#  |  Type: CODE_SMELL  |  Severity: Major

Tags: symbolic-execution

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