Search code examples
c#finalizer

Why is it not a good idea to serialize an object in its finalizer?


In the book Headfirst C#, I get the point of view that "it's not a good idea to serialize an object in its finalizer, since serialization requires the whole object tree to be in the heap, but you may end up with missing vital part of your program because some objects might’ve been collected before the finalizer ran."

My question is that since my object get a reference to others (that means there is at least one reference to other objects) , how could they be garbage-collected before my finalizer runs?


Solution

  • The problem with finalizers is that they provide very few guarantees:

    • they're not guaranteed to ever run
    • you can't predict when they will run
    • when they do run, it's possible that some objects they reference have already been finalized, so your object might not be in a valid state

    Eric Lippert has two great blog posts about this:

    In any case, 99% of the classes you'll ever write should probably not have a finalizer at all. There are very few cases where they're actually necessary. If you need to perform cleanup after you're done using an object, implement IDisposable instead, which at least you can control in a deterministic way.