S2930: Not detecting Dispose() call when object is explicitly cast to IDisposable

  • What language is this for? C#
  • Which rule? S2930 “IDisposables” should be disposed
  • Why do you believe it’s a false-positive/false-negative? The class implements a Dispose() method disposing of the IDisposable member.
  • Are you using
    • SonarQube Community Build, 26.2
    • SonarQube for IDE - Visual Studio, 9.6.0.16157, in connected mode
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        public void Dispose()
        {
            ((IDisposable)_cancellationTokenSource).Dispose();
        }

The cast to IDisposable was provided by the IDE’s code fix on the IDisposable interface (“Implement interface through ‘_cancellationTokenSource’”). Removing the cast causes S2930 to no longer be detected. While it’s redundant in this case, there are other IDisposable implementations where it is not (i.e. any where IDisposable is explicitly implemented).

Thanks for the report and the clear reproducer — this is indeed a false positive.

The rule tracks whether disposable fields are disposed by scanning for .Dispose() calls on the field. When the call is made through an explicit cast — ((IDisposable)_field).Dispose() — the analyzer fails to recognize the receiver as the field in question and incorrectly concludes it was never disposed.

We have created an internal reproducer for this case and the fix has been added to our backlog.