It seems you have nothing to interfere with implementing IDisposable in your child class, take this example:
public class DisposableParent : IDisposable { public void Dispose() { Console.WriteLine("The parent was disposed."); } } public class DisposableChild : DisposableParent, IDisposable { public new void Dispose() { base.Dispose(); Console.WriteLine("The child was disposed."); } } public class Program { public static void Main() { using (DisposableChild c = new DisposableChild()) { } Console.ReadKey(true); } }
Gives the following output:
The parent has been deleted.
The baby has been removed.
The compiler warns that it hides the allocation of the parent class in the child, so using the new operator eliminates this warning, just make sure you call the base Dispose class from the child class (and implement its correct path).
The utility for the child will become something like:
public class DisposableChild : DisposableParent, IDisposable { private bool _disposed = false; public new void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { if (!_disposed) { base.Dispose(); Console.WriteLine("The child was disposed."); _disposed = true; } } } }
And yes, this works if you do something like:
using (DisposableParent p = new DisposableChild()) { }
But something like this might break it:
public class Program { public static void Main() { DisposableChild c = new DisposableChild(); DisposeOfIt(c); Console.ReadKey(true); } public static void DisposeOfIt(DisposableParent p) { p.Dispose(); } }
Only prints that the parent has been deleted. Therefore, if you used this method, you need to be careful in managing the lifetime of your objects.