Skip to content

CA1517 false positive when span elements are mutated via foreach (ref var ...) #56292

Closed

Description

@xPaw

Version Used: .NET SDK 11.0.100-rc.1.26425.128 (Microsoft.CodeAnalysis.NetAnalyzers 11.0.100-rc.1.26425.128+3551975be08744f0418857c5bed8ab1545c5dd47)

Steps to Reproduce:

  1. Create a net11.0 project with <AnalysisMode>All</AnalysisMode>.
  2. Add the following code:
using System;

struct Item
{
    public int Value;
}

static class Program
{
    static void Main()
    {
        var items = new Item[4];
        Increment(items);
        Console.WriteLine(items[0].Value);
    }

    static void Increment(Span<Item> items)
    {
        foreach (ref var item in items)
        {
            item.Value++;
        }
    }
}
  1. Build.

Diagnostic Id:

CA1517: Parameter 'items' can be declared as 'ReadOnlySpan<Item>' instead of as 'Span<Item>'

Expected Behavior:

No diagnostic. The method writes to the span elements through the ref iteration variable, so the parameter cannot be ReadOnlySpan<Item>.

Actual Behavior:

CA1517 is reported. Applying the suggested change to ReadOnlySpan<Item> fails to compile:

error CS8331: Cannot assign to method 'Current.get' or use it as the right hand side of a ref assignment because it is a readonly variable

The analyzer does not appear to treat foreach (ref var x in span) as a mutating use of the span.

Activity

  1. transferred this issue fromdotnet/roslynon Sep 14, 2026
  2. added
    untriaged
    on Sep 14, 2026
  3. locked and limited conversation to collaborators on Sep 14, 2026
  4. unlocked this conversation on Sep 14, 2026
  5. github-actions commented on Sep 14, 2026

    @github-actions
    Contributor

    🎯 Agentic Issue Triage

    Triage Assessment:

    Similar issues: #53388 (potentially related)

    ➡️ Summary: CA1517 wrongly suggests ReadOnlySpan<T> for a parameter whose elements are mutated via foreach (ref var ...). Analyzer should recognize ref-foreach mutation as a write use.

    Generated by 🏷️ Issue Triage for #56292 · copilot · auto · 63.6 AIC · ⌖ 8.68 AIC · ⊞ 14.6K · ◷

  6. removed
    untriaged
    on Sep 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions