#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: