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?
The problem with finalizers is that they provide very few guarantees:
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.