3

I have this class:

public abstract class ImplementsIDisposable : IDisposable
{
    public abstract void Dispose();

    private class InnerClass : ImplementsIDisposable
    {
        private bool disposedValue;

        public override void Dispose()
        {
            if (!disposedValue)
            {
                doSomething();
                disposedValue = true;
            }

            GC.SuppressFinalize(this);
        }
    }
}

And Code Analysis is throwing this message:

CA1063 Modify Dispose() so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance and then returns.

And this one:

CA1063 Ensure that Dispose() is declared as public and sealed.

Both in the this line:

public abstract void Dispose();

Can it be that it wants Dispose() to be implemented in ImplementsIDisposable instead of InnerClass?

MauriR
  • 537
  • 10
  • 20

2 Answers2

3

There is no reason why public Dispose() should be virtual and much less abstract.

You need to check out the dispose pattern and implement it correctly. The warnings are hinting how you should do it but they can be rather cryptic unless you know how the pattern goes to begin with.

You can read about the Dispose Pattern here, it’s rather simple.

And of course, don’t miss this canonical SO answer on the subject.

InBetween
  • 32,319
  • 3
  • 50
  • 90
1

I tried to follow the accepted answer, but I kept running into a wall because the last two lines of my method were indeed Dispose(true) and GC.SupressFinalize(this). It turns out that the warning did not make me understand that these should be the ONLY lines in the method, leaving something like the below. I believe the first link in the accepted answer actually does explain this difference, but I didn't read it as carefully as maybe I should have.

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

protected virtual void Dispose(bool disposing)
{
    try
    {
        if (disposing)
        {
            // call Dispose on all your disposable fields/properties
        }
    }
    finally
    {
        // free all unmanaged resources here.  Note that this is not in an else block.
    }
}

Credit to https://netvignettes.wordpress.com/2011/06/29/how-to-implement-dispose-properly/ for getting me on track.

Brandon Barkley
  • 720
  • 6
  • 21