← back to index

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

Language: VB.NET  |  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

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

Articles & blog posts