Base on the C# specification, 10.13 Destructors
” When an instance is destructed, the destructors
in that instance’s inheritance chain are called, in order, from most derived to least derived.”
My questions are:
why destructors are called, in order, from most derived to least derived?
why not are called, in order, from least derived to most derived or other order?
Because objects are built up from the least derived to the most derived, so they have to be torn down from the most derived to the lest derived.
The deriving class knows about base class, but the base class doesn’t know about the derived class. If you would tear down the object from the least derived class to the most derived class, the base class would remove things that the derived class might need in the process.
Consider for example that the base class has a list of objects:
The derived class adds something to each item in the list:
When the object is torn down, the derived class needs access to the list in order to clean up what it added. If the base class was destructed first, the derived class wouldn’t have access to the objects in the list.
(Note however that
IDisposableis normally a better option to handle controlled cleanup of objects.)