المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : C++ virtual destructor in C#? Why not?



C# Programming
05-16-2009, 04:40 PM
hello

Need clarification on why we have no C# virtual destructor - here's my understanding.

1. Unmanaged resources are freed by calling Dispose (true/false), managed resources are freed by call to Dispose(true).
2. Managed memory is freed by call to Dispose - Base class should mark Dispose virtual, Derived class should explicitly "override" base class Dispose and "Base.Dispose" should be called in Derived.Dispose (this way both Derived/Base Dispose are called in chain)

Question:
1. Should we make Base.Finalize (~Base really in C# syntax) virtual? Should we implement Derived.Finalize (~Derived in C# syntax)?
2. C++ destructor is C# destructor (or Finalizer) - now SINCE we really want to release resource (expensive ones in particular) in Dispose (deterministically, unlike ~Derived or ~Base), what really I'm asking is, why not "Virtual destructor" same style as C++: http://www.codersource.net/cpp_virtual_destructors.html[^ (http://www.codersource.net/cpp_virtual_destructors.html)]

In C++, if you declared destructor virtual, and "delete oDerived", BOTH destructor from Base and Derived are invoked (~Derived then ~Base). Why is this NOT the behavior in C#? That you need to call Base.Dispose explicitly in Derived.Dispose, relying on programmer to make sure both are called? Seems like C++ virtual destructor is cleaner?

Thanks

REF:
http://www.codersource.net/cpp_virtual_destructors.html[^ (http://www.codersource.net/cpp_virtual_destructors.html)]
http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx[^ (http://msdn.microsoft.com/en-us/library/b1yfkh5e(VS.71).aspx)]

dev