I am dealing with following case. I have a base class that have the IDisposable pattern, it means that it have the public virtual Dispose() method and the protected virtual Dispose(bool) method. But I am not able to implement this patter in the derived class in such way that I will not receive any CA warnings. Please consider following example:
public class UtilizeClass : IDisposable
{
private MyData data;
public UtilizeClass()
{
data = new MyData();
}
public void Dispose()
{
data.Dispose(); // Cannot use Dispose(bool) because it is protected.
}
}
public class MyData : Base, IDisposable
{
// Here we have some managed resources that must be disposed.
// How to implement the pattern?
}
public class Base : IDisposable
{
public virtual void Dispose() { }
protected virtual void Dispose(bool disposing) { }
}
All the time I receive contradictory CA warnings in the MyData class. For example: delete the Dispose() and move it logics to Dispose(bool).
Thank you very much for answer and help.
Your base class shouldn’t have
void Dispose()be virtual, it should be implemented and invoke the virtualvoid Dispose(bool disposing)as part of its implementation.For more detail, and an alternate API that’s slightly clearer, check out:
http://haacked.com/archive/2005/11/18/acloserlookatdisposepattern.aspx