Compartir a través de


Using C# and Managed Extensions for C++ Destructor Syntax

You cannot call or override the Object.Finalize method from the C# or the Managed Extensions for C++ programming languages. C# and the Managed Extensions provide destructors as the mechanism for writing finalization code. You must use the destructor syntax in C# and the Managed Extensions to perform cleanup operations. This syntax is convenient because it implicitly calls the Finalize method for an object's base class. This guarantees that Finalize is called for all levels of destructors from which the current class is derived.

The following code example is written for a destructor.

~MyClass()
{
   // Perform some cleanup operations here.
}

This code implicitly translates to the following.

protected override void Finalize()
{
   try
   {
      // Perform some cleanup operations here.
   }
   finally
   {
      base.Finalize();
   }
}

Note   Although they look similar, the C# and the Managed Extensions destructors do not have the same semantics as unmanaged C++ destructors. Managed code does not support anything similar to the C++ destructor semantics.

See Also

Cleaning Up Unmanaged Resources | Overriding the Finalize Method | Object.Finalize Method | C# Language Reference 1.7.9 Destructors