I am having following class hierarchy –
//Abstract Class1 in library1 (Can't modify this)
public abstract class absClass1 : IDisposable
{
public abstract int AddTwoNumbers(int Num1, int Num2);
// Some other overrides, abstract methods and concrete methods
void Dispose()
{
// Standard Dispose impl.
}
}
//Abstract Class2 in library2
public abstract class absClass2 : absClass1
{
//Implementing AddTwoNumbers
public override int AddTwoNumbers(int Num1, int Num2)
{
return Num1+Num2;
}
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
// Some other overrides, abstract methods and concrete methods
protected override void Dispose(bool disposing)
{
if (!IsDisposed)
{
//Cleanup
}
base.Dispose(disposing);
}
}
//Derived class from absClass2 in library3
public sealed class absDerived1 : absClass2
{
//Implementing MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1*Num2;
}
// Some other overrides, abstract methods and concrete methods
protected override void Dispose(bool disposing)
{
if (!IsDisposed)
{
// Cleanup
}
base.Dispose(disposing);
}
}
//... Some more implementation of absClass2 like absDerived2 etc.
// can be there in other library4...
I want to dispose objects in both absClass2 and absDerived, is there any problem in overriding Dispose(bool) in both these classes? Is there any problem with this design? How can this be improved?
This currently won’t compile, but as you aren’t asking why it doesn’t compile I’m going to guess you just left out the
void Dispose()definition for brevity.This will be fine so long as you call into
base.Disposecorrectly and only worry about disposing the stuff local to the current class and not in a base class – as you are relying onbase.Disposeto do this for you.Calling
base.<member>simply calls the direct base type of the current type, so in your caseabsDerivedgoes toabsClass2, which goes toabsClass.My only observation would be you need to be careful on disposing the current type’s stuff before calling
base.Dispose. Depending on how stuff relates, you might want to dispose the base stuff first, then the current type – but this is entirely dependent on what you are actually disposing and if order is important.