dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.13k stars 4.04k forks source link

False positive CS0169 reported for structs with used fixed buffer #69738

Open controlflow opened 1 year ago

controlflow commented 1 year ago

Version Used:

main branch

Steps to Reproduce:

Compile the following code:

// ReSharper disable UnusedVariable

unsafe class NotUsedField
{
  private S _s; // warning CS0169: The field 'NotUsedField._s' is never used

  struct S
  {
    public fixed int Buffer[10];
  }

  public int ReadFirst()
  {
    fixed (int* ptr = _s.Buffer)
    {
      return *ptr;
    }
  }

  public void WriteFirst(int value)
  {
    fixed (int* ptr = _s.Buffer)
    {
      *ptr = value;
    }
  }
}

Diagnostic Id:

CS0169

Expected Behavior:

No CS0169 produced, since struct can be is used for both read and write if it's fixed buffer field is used.

Actual Behavior:

False positive compiler warning CS0169 produced.

jcouv commented 1 year ago

FWIW, this behavior also existed in the native compiler.

We could:

  1. leave as-is (usage in fixed isn't considered a read or write)
  2. treat usage in fixed as a read/write (silence this warning, trading a false alarm for erroneous silence in some cases)
  3. do some alias analysis
jaredpar commented 1 year ago

This pattern is roughly equivalent to the following


struct S {
    int _field;  
    void G() => M(ref _field);
    void M(ref int i) { }
}

There is an implicit & in the fixed case. Given we don't warn here I would say not warning on the fixed case is reasonable.

I'd also say it's not terribly high priority given the behavior's been this way since C# 1.0.