SonarSource / sonar-dotnet

Code analyzer for C# and VB.NET projects
https://redirect.sonarsource.com/plugins/csharp.html
GNU Lesser General Public License v3.0
787 stars 226 forks source link

Fix S3267 FP: Cannot use local variable of byref-like type 'ReadOnlySpan<>' inside lambda expression #9685

Open dimon4egkl opened 1 week ago

dimon4egkl commented 1 week ago

Description

S3267 Some suggestions to simplify the code by rewriting it using LINQ cannot be applied when ref struct types are involved.

Repro steps

ReadOnlySpan<char> stringToCompare = "example".AsSpan();
string[] stringValues = ["example", "another string"];
var isMatchFound = false;
// S3267: loop should be simplified to LINQ
foreach (var value in stringValues)
{
    if (value.AsSpan().Equals(stringToCompare, StringComparison.Ordinal))
    {
        isMatchFound = true;
        break;
    }
}

ReadOnlySpan is a ref struct and can not be used inside lambda expressions.

// Cannot use local variable 'stringToCompare' of byref-like type 'ReadOnlySpan<char>' inside lambda expression;
ReadOnlySpan<char> stringToCompare = "example".AsSpan(); 
string[] stringValues = ["example", "another string"];
var result = stringValues.Any(value => value .AsSpan().Equals(stringToCompare, StringComparison.Ordinal));

Expected behavior

I didn't expect any diagnostics to be emitted.

Actual behavior

False positive.

Known workarounds

#pragma warning disable S3267

Related information

alex-meseldzija-sonarsource commented 5 hours ago

Hi there, I believe this is a duplicate of #8430 Which we have reproduced here Thanks for raising this!