Destructor and finalizer
#include "stdafx.h" using namespace System; using namespace System::Collections::Generic; ref class MyClass{ static List<MyClass^>^ instanceTrackingList; static MyClas(){ instanceTrackingList = gcnew List<MyClass^>; } MyClass(String^ s) { Label = s; instanceTrackingList->Add( this ); } property String^ Label; static int EnumerateInstances() { int i = 0; for each (MyClass^ r in instanceTrackingList) { i++; Console::WriteLine( r->Label ); } return i; } ~MyClass() // destructor { this->!MyClass(); } !MyClass() // finalizer { instanceTrackingList->Remove( this ); } }; int main(){ MyClass r1("ABC"); MyClass^ r2 = gcnew MyClass("XYZ"); int count = MyClass::EnumerateInstances(); Console::WriteLine("Object count: " + count); delete r2; count = MyClass::EnumerateInstances(); Console::WriteLine("Object count: " + count); }