Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA2213 warning when using ?. (null-conditional Operator) to call Dispose

I'm implementing IDisposable, and in my Dispose() method when calling Dispose() on other managed resources I'm using the ?. operator like so:

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(disposing)
        {
            _ChangeLock?.Dispose();
        }
    }

I'm still getting the following code analysis error:

CA2213: 'MyClass' contains field 'MyClass._ChangeLock' that is of IDisposable type: 'ReaderWriterLockSlim'. Change the Dispose method on 'MyClass' to call Dispose or Close on this field.

If I change to a standard null check, the code analysis warning goes away:

if(_ChangeLock != null)
    _ChangeLock.Dispose();

Is there something wrong with using the null-conditional operator the way I am, or is this code analysis rule outdated, or what?

like image 620
StuartMorgan Avatar asked Mar 25 '16 22:03

StuartMorgan


1 Answers

This is a known issue with FxCop.

It appears they have decided not to fix it:

We decided to cut [CA2213] because it is very hard to get it right without deeper analysis, tracking variables and possibly having annotations. The current implementation is very noisy and has a lot of false positives and the value of the rule is not worth all the noise it generates.

like image 163
BJ Myers Avatar answered Oct 04 '22 00:10

BJ Myers