Compartilhar via


Overriding the Finalize Method 

A Finalize method acts as a safeguard to clean up resources in the event that your Dispose method is not called. You should only implement a Finalize method to clean up unmanaged resources. You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically. By default, the Object.Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object's memory, you must override this method in your class.

NoteNote

You cannot override the Finalize method in the C# or C++ programming languages. In C#, use destructor syntax to implement the Finalize method. In version 2.0 of the .NET Framework, C++ provides its own syntax for implementing the Finalize method, as described in Destructors and Finalizers in Visual C++. In earlier versions, C++ used destructor syntax for the Finalize method, as C# does.

The scope of the Object.Finalize method is protected. You should maintain this limited scope when you override the method in your class. By keeping a Finalize method protected, you prevent users of your application from calling an object's Finalize method directly.

An object's Finalize method should release all resources that are held onto by the object. It should also call the Finalize method for the object's base class. An object's Finalize method should not call a method on any objects other than that of its base class. This is because the other objects being called could be collected at the same time as the calling object, such as in the case of a common language runtime shutdown.

If you allow any exceptions to escape the Finalize method, the system assumes that the method returned, and continues calling the Finalize methods of other objects.

See Also

Reference

Object.Finalize Method

Concepts

Implementing a Dispose Method
Destructor Syntax in C# and C++

Other Resources

Handling and Throwing Exceptions
Exception Handling Fundamentals