3

I have a class that implements IDisposable. I changed my Dispose() method from this:

public void Dispose()
{
    if (AccountCreateResetEvent != null)
    {
        AccountCreateResetEvent.Dispose();
        AccountCreateResetEvent = null;
    }
}

to this:

public void Dispose()
{
    AccountCreateResetEvent?.Dispose();
    AccountCreateResetEvent = null;
}

Now I get the following error when running Code Analysis:

'Adapter' contains field 'Adapter.AccountCreateResetEvent' that is of IDisposable type: 'AutoResetEvent'. Change the Dispose method on 'Adapter' to call Dispose or Close on this field.

Is this a quirk of Code Analysis or am I doing something wrong here?

EDIT: Simple full class declaration that reproduces the problem

using System;
using System.Threading;

namespace IDisposableProblem1
{
    public sealed class Account : IDisposable
    {
        private AutoResetEvent AccountResetEvent = new AutoResetEvent(false);

        public void Dispose()
        {
            AccountResetEvent?.Dispose();
            AccountResetEvent = null;
        }
    }
}
Sean Beanland
  • 1,098
  • 1
  • 10
  • 25
  • Do you have any 3rd party analyzer extensions installed, or any analyzer NuGet packages installed in the project? – mason Dec 04 '15 at 17:49
  • @mason, no, I'm only using the built in Code Analysis tool in Visual Studio 2015. – Sean Beanland Dec 04 '15 at 17:50
  • Click the "New Issue" button on [this page](https://github.com/dotnet/roslyn/issues). – Hans Passant Dec 04 '15 at 17:57
  • can you share full code then only we can understand whats going on. – Pankaj Gupta Dec 04 '15 at 19:14
  • @PankajGupta, added a simple class that reproduces the problem. – Sean Beanland Dec 04 '15 at 19:46
  • 4
    Just a guess: `AccountResetEvent?.Dispose();` equivalent to `var tempVariable=AccountResetEvent; if(tempVariable!=null){tempVariable.Dispose()}`, so you calling `Dispose` on `tempVariable` but not on `AccountResetEvent`, and that confuse Code Analysis tool. – user4003407 Dec 04 '15 at 20:50
  • Possible duplicate of [CA2213 warning when using ?. (null-conditional Operator) to call Dispose](https://stackoverflow.com/questions/36229230/ca2213-warning-when-using-null-conditional-operator-to-call-dispose) – BJ Myers Nov 25 '18 at 22:49

0 Answers0