C# FAQ: Are destructors the same in Cplusplus and CSharp


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

Are destructors the same in C++ and C#?

No. Although, they look the same, C++ and C# destructors are—in fact—very different. C# destructor syntax using the familiar tilde (~) character is but a compiler cover for an override of the Finalize method of System.Object.

This Finalize method is called by the garbage collector (GC) when it discovers that an object is not being referenced. Afterwards, the garbage collector frees the memory associated with the object. The difference is that the garbage collector does not guarantee when this procedure will happen. In fact, it may be a long time after the application has finished with the object before the garbage collector takes action. This uncertainty of timing is dubbed non-deterministic finalization. Accordingly, C# destructors are unsuitable for releasing scarce resources, e.g. database connections, file handles, etc.

To achieve deterministic destruction, a class must contain a method dedicated to that purpose. Typically, a class will implement the IDisposable interface. And, the Dispose() method of the object must be called when the object is no longer needed. The 'using' keyword of C# can be used to write a clean Dispose() method.

See also



Personal tools