Fix S4456/S4457 FN: Recognize ArgumentNullException.ThrowIfNull()
Description
The next analyzers do not recognize the usage of ArgumentNullException.ThrowIfNull(), which was added in .NET 6.
- S4456: Parameter validation in yielding methods should be wrapped
- S4457: Parameter validation in "async"/"await" methods should be wrapped
I'm reporting both in a single issue, because they share the same base class to detect the null-check.
Repro steps
The next code snippet correctly reports S4456 and S4457. When commenting out the #define USE_IF_STATEMENT line, the warnings disappear, which is unexpected (false negative).
#define USE_IF_STATEMENT
public sealed class Repro
{
public IEnumerable<char> Enumerate(string source)
{
#if USE_IF_STATEMENT
if (source == null) throw new ArgumentNullException(nameof(source));
#else
ArgumentNullException.ThrowIfNull(source);
#endif
foreach (char ch in source)
{
yield return ch;
}
}
public async Task RunAsync(string source)
{
#if USE_IF_STATEMENT
if (source == null) throw new ArgumentNullException(nameof(source));
#else
ArgumentNullException.ThrowIfNull(source);
#endif
await Task.Yield();
}
public async IAsyncEnumerable<char> EnumerateAsync(string source)
{
#if USE_IF_STATEMENT
if (source == null) throw new ArgumentNullException(nameof(source));
#else
ArgumentNullException.ThrowIfNull(source);
#endif
await Task.Yield();
foreach (char ch in source)
{
yield return ch;
}
}
}
Expected behavior
Warnings appear, regardless of using if or ArgumentNullException.ThrowIfNull() to perform the null check.
Actual behavior
Warnings do not appear when using ArgumentNullException.ThrowIfNull().
Known workarounds
Do not use ArgumentNullException.ThrowIfNull() for null checks.
Related information
- C#/VB.NET Plugins version: SonarAnalyzer.CSharp (NuGet package) v8.40.0.48530
- Visual Studio version: Microsoft Visual Studio Community 2022 (64-bit) v17.2.3
- MSBuild version: Microsoft (R) Build Engine version 17.2.1+52cd2da31 for .NET Framework, v17.2.1.25201
- dotnet version: v6.0.300
- SonarScanner for .NET version (if used): ?
- Operating System: Windows 10 Enterprise 21H2 x64 ENU, v19044.1706
Thanks a lot @bart-vmware , I confirm the FN and documented it in a test case.