CA1517 false positive when span elements are mutated via `foreach (ref var ...)`
- Dominant language
- C#
- Stars
- 3.2k
- Forks
- 1.3k
- PR merge metrics
- PR metrics pending
Description
**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 `All`.
2. Add the following code:
```csharp
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 items)
{
foreach (ref var item in items)
{
item.Value++;
}
}
}
```
3. Build.
**Diagnostic Id**:
`CA1517: Parameter 'items' can be declared as 'ReadOnlySpan' instead of as 'Span'`
**Expected Behavior**:
No diagnostic. The method writes to the span elements through the `ref` iteration variable, so the parameter cannot be `ReadOnlySpan`.
**Actual Behavior**:
CA1517 is reported. Applying the suggested change to `ReadOnlySpan` 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.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.