GU0019
January 1, 2022 ยท View on GitHub
LinqOrDefault when IEnumerable
| Topic | Value |
|---|---|
| Id | GU0019 |
| Severity | Warning |
| Enabled | True |
| Category | Gu.Analyzers.Correctness |
| Code | InvocationAnalyzer |
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...")]