dotnet / roslyn-analyzers

MIT License
1.55k stars 460 forks source link

incorrect suggestion of CA1854 Prefer a "TryGetValue" call over a Dictionary indexer access guarded by a "ContainsKey" check to avoid double lookup #7295

Open wstaelens opened 2 months ago

wstaelens commented 2 months ago

Analyzer

Diagnostic ID: CA1854 Prefer a "TryGetValue" call over a Dictionary indexer access guarded by a "ContainsKey" check to avoid double lookup

Analyzer source

latest .net 8 version and vs pro 2022 17.9.6

Describe the bug

    public Dictionary<int, Dictionary<int, bool?>> PermissionsData { get; set; }

 public void Combine(IPermission p) {
  // ...... some logic
     if (p == null)
        return;

      TypePermission otherP = (TypePermission)p;

      foreach (int objId in otherP.PermissionsData.Keys)
      {
        if (PermissionsData.ContainsKey(objId))
          CombineEntityPerms(objId, otherP.PermissionsData[objId]);
        else
          PermissionsData.Add(objId, otherP.PermissionsData[objId]);
      }
// some logic...
}

image

it suggest to do a trygetvalue and use value but doesn't see that PermissionsData.ContainsKey(objId) and otherP.PermissionsData[objId] are different.