Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Destructor/Dispose of the base class?

In C#, as mentioned in the Documentation, and this nice post's accepted answer, it's stated that classes don't inherit the Destructor of their parent class.

The question : If I want to make sure to dispose the private elements of the base class, is the proper way to implement IDisposable in all the child class, and in the Dispose method, call base.Dispose()?

It looks alright to do so, but I would have preferred a way which wouldn't require implementation in all of the child classes.

like image 856
Tipx Avatar asked Apr 20 '11 14:04

Tipx


1 Answers

You should follow the Disposable pattern here. It also caters for inheritance.

The interesting part here is "destructors don't inherit", I'm not sure what to make of that. I wrote a little test but to my relief you only need to write a destructor in the base-class.

So the children are uncoupled from the base-class unmanaged resources. They can override Dispose(bool) to cleanup their own affairs.

But I made a comment because I see too many programmers implementing the full pattern just to handle managed resources.

From a general design perspective, a Disposable class would better be sealed.

like image 177
Henk Holterman Avatar answered Oct 04 '22 21:10

Henk Holterman