C# rule "Empty collections should not be accessed or iterated" should ignore TryAdd()

  • versions used (SonarQube 7.4, Scanner: MSBuild Scanner, Language C#)
  • error observed: Empty Collection is accessed with TryAdd, but the above warning is given.
  • steps to reproduce: Use TryAdd on an empty collection in C#
  • potential workaround: none

“Empty collections should not be accessed or iterated.”
This error is erroneously shown when you use TryAdd() and not Add().

There should probably be another rule for using TryAdd(), TryParse() etc. and not checking the results.

Hi @BogusDude. I am trying to reproduce this FP but cannot… The below snippet does not raise S4158 with SonarAnalyzer for C# 7.12 for me…

class Program
{
    static void Main(string[] args)
    {
        var x = new Dictionary<string, string>();
        x.TryAdd("x", "y");
    }
}

What version of dotnet core were you using?

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.