0

I have a problem that was not present until the most recent VS2019 update (16.8.1)

public class ReproClass : IDisposable
{
    private readonly Mutex _mtx = new Mutex();
    public void Dispose() => _mtx?.Dispose();
}

produces:

Severity Code Description Project File Line Suppression State Error CA2213 'ReproClass' contains field 'ReproClass._mtx' that is of IDisposable type: 'Mutex'. Change the Dispose method on 'ReproClass' to call Dispose or Close on this field. ShutterModeler path_to\ReproClass.cs 10 Active

I'm using "Code Analysis" with "Microsoft Manager Miniumum Rules" set.

This seems related to Code Analysis Warning CA2213 - Call Dispose() on IDisposable backing field but I'm not using FXcop nor a property.

How to solve this ?

Soleil
  • 6,404
  • 5
  • 41
  • 61
  • 1
    I'm curious.... does the problem go away if you remove the `?` symbol? – John Wu Nov 14 '20 at 03:17
  • Don't take all warnings for granted, use your common sense and don't fear about suppressing. – aybe Nov 14 '20 at 03:17
  • I'm with @JohnWu here. You know that that `_mtx` cannot be null in the provided example so I'd suggest removing the `?` (null propagation operator). – WBuck Nov 14 '20 at 03:21
  • @JohnWu Indeed, the Error goes away with the null check propagator being removed. – Soleil Nov 14 '20 at 03:23

1 Answers1

0

As suggested by John Wu, the null propagation operator was the culprit. CA2213 goes away in this implementation:

public class ReproClass : IDisposable
{
    private readonly Mutex _mtx = new Mutex();
    public void Dispose() => _mtx.Dispose();
}

This implementation reduces the cyclomatic complexity to 1, which is desired in Dispose().

Soleil
  • 6,404
  • 5
  • 41
  • 61