False positive for S4158

Hi,

I have a false positive for S4158 where a list is filled by another function and then iterated.

  internal class FalsePositiveS4158
  {
    public List<int> Numbers { get; set; }

    public void Initialize()
    {
      Numbers = new List<int>();
      InitializeNumbers();

      // S4158	When a collection is empty, iterating it has no effect. Doing so anyway is likely a bug;
      // either population was accidentally omitted, or the iteration needs to be revised.
      foreach (var number in Numbers)
      {
        System.Diagnostics.Debug.WriteLine(number);
      }
    }

    private void InitializeNumbers()
    {
      Numbers.Add(1);
      Numbers.Add(2);
      Numbers.Add(3);
    }
  }

Using

  • Sonarlint Visual Studio 8.0.0.92083

Hi @Valentijn!
I confirm this as an FP. You can track the progress of this issue here.

Thanks!