Finalizers called from partially constructed objects

Did you know that finalizers are called from partially constructed objects? I certainly didn’t. If an exception is thrown from a class constructor, that object is considered “partially constructed” - and its finalizer is still run when the object is garbage collected. Chris Brumme mentioned this four years ago when he helped us understand that it’s hard to implement Finalize properly: “Your Finalize method must tolerate partially constructed instances.”

A coworker discovered this fact when he was unit testing a class that called Debug.Fail in its finalizer to make sure that its instances were being disposed properly. He passed an invalid argument to the constructor to verify that an exception would be thrown - but then found that the call to Debug.Fail in the finalizer was causing tests to fail.

We couldn’t figure out a good way to determine whether an object is partially constructed, so we just had to hack around the problem. Any better ideas for detecting undisposed objects?

Posted by Ed Ball on April 08, 2008