GU0019

January 1, 2022 ยท View on GitHub

LinqOrDefault when IEnumerable

TopicValue
IdGU0019
SeverityWarning
EnabledTrue
CategoryGu.Analyzers.Correctness
CodeInvocationAnalyzer

Description

Methods like FirstOrDefault is a common regression when changing from class to struct.

Motivation

Code like below has frequent regressions when refactoring from class to struct

if (xs.FirstOrDefault() is { } x)
{
    ...
}

## How to fix violations

Adding `FirstOrNull()` is clearer.

```cs
if (xs.FirstOrNull() is { } x)
{
    ...
}

<!-- start generated config severity -->
## Configure severity

### Via ruleset file.

Configure the severity per project, for more info see [MSDN](https://msdn.microsoft.com/en-us/library/dd264949.aspx).

### Via #pragma directive.
```C#
#pragma warning disable GU0019 // LinqOrDefault when IEnumerable<struct>
Code violating the rule here
#pragma warning restore GU0019 // LinqOrDefault when IEnumerable<struct>

Or put this at the top of the file to disable all instances.

#pragma warning disable GU0019 // LinqOrDefault when IEnumerable<struct>

Via attribute [SuppressMessage].

[System.Diagnostics.CodeAnalysis.SuppressMessage("Gu.Analyzers.Correctness", 
    "GU0019:LinqOrDefault when IEnumerable<struct>", 
    Justification = "Reason...")]