Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
dimon4egkl opened this issue Oct 14, 2024 · 1 comment
Labels
Area: C# C# rules related issues. Type: False Positive Rule IS triggered when it shouldn't be.

Comments

@dimon4egkl
Copy link

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

  • SonarCloud.io
  • JetBrains Rider 2024.1.1
  • dotnet 8.0.403
  • SonarScanner for .NET version 2.3.2
  • RedHat
@alex-meseldzija-sonarsource

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: C# C# rules related issues. Type: False Positive Rule IS triggered when it shouldn't be.
Projects
None yet
Development

No branches or pull requests

3 participants