#737 – When to Implement a Finalizer

In C#, you implement a finalizer using the destructor (~) syntax.  The finalizer is called by the system when the object is being destroyed.

In general, you rarely need to implement a finalizer.  Rules of thumb for implementing a finalizer include:

  • Implement a finalizer only when the object has unmanaged resources to clean up (e.g. file handles)
  • Do not implement a finalizer if you don’t have unmanaged resources to clean up
  • The finalizer should release all of the object’s unmanaged resources
  • Implement the finalizer as part of the dispose pattern, which allows for deterministic destruction
  • The finalizer should only concern itself with cleanup of objects owned within the class where it is defined
  • The finalizer should avoid side-effects and only include cleanup code
  • The finalizer should not add references to any objects, including a reference to the finalizer’s own object
  • The finalizer should not call methods in any other objects