Peter, I have a question...
When you say "there's no practical way for the compiler to automatically
create a Finalize method that would do anything useful"...
Is this statement true because at runtime there's really no way for the
CLR
to know 'what' unmanaged resources would have to be cleaned-up?
Sort of. I mean, I was speaking of the compiler, but yes...the same issue
applies to the run-time as well. By definition, unmanaged resources are
unknown to the run-time. But not only can't the CLR know which resources
would have to be cleaned up, it also doesn't have any way to know in a
reliable way how to clean them up. For a subset of all unmanaged
resources there are assumptions the CLR could make about how to clean them
up, but they wouldn't necessarily be correct in all situations, and for
some unmanaged objects the CLR just wouldn't know how at all.
Really, I think my statement didn't go far enough. It would theoretically
be possible to imbue the compiler and/or run-time with knowledge about
unmanaged objects and how to dispose them, at least for a broad class of
unmanaged objects. But because the unmanaged objects don't themselves
have a well-defined model for declaring when they are no longer in use,
there's no reliable way for the compiler or run-time to know whether it's
actually safe to dispose them or not.
Basically, for unmanaged objects, the lifetime is determined by the order
of execution of code, which isn't something that the run-time can inspect
in any practical fashion (and the compiler definitely can't, since it
doesn't even have access to all of the code that might execute). Managed
objects can be properly handled because their lifetime is entirely
determined by a present state that is (relatively) easily inspected: is
the object reachable or not? This has nothing to do with what code might
execute in the future, it only has to do with what the data looks like
now. But you can't do that with unmanaged objects.
So, any finalizer has to be written explicitly by the programmer, using
that programmer's knowledge of how the unmanaged object is going to be
used and the right way to clean it up, assuming it needs cleaning up at
all.
Pete