Information Technology Reference
In-Depth Information
to call its finalizer again. If you actually need to finalize a resurrected
object, it won't happen. Second, some of your resources might not be avail-
able. The GC will not remove from memory any objects that are reach-
able only by objects in the finalizer queue, but it might have already
finalized them. If so, they are almost certainly no longer usable. Although
the members that BadClass owns are still in memory, they will have likely
been disposed of or finalized. There is no way in the language that you can
control the order of finalization. You cannot make this kind of construct
work reliably. Don't try.
I've never seen code that has resurrected objects in such an obvious fash-
ion, except as an academic exercise. But I have seen code in which the final-
izer attempts to do some real work and ends up bringing itself back to life
when some function that the finalizer calls saves a reference to the object.
The moral is to look very carefully at any code in a finalizer and, by exten-
sion, both Dispose methods. If that code is doing anything other than
releasing resources, look again. Those actions likely will cause bugs in your
program in the future. Remove those actions, and make sure that finaliz-
ers and Dispose() methods release resources and do nothing else.
In a managed environment, you do not need to write a finalizer for every
type you create; you do it only for types that store unmanaged types or
when your type contains members that implement IDisposable. Even if
you need only the Disposable interface, not a finalizer, implement the
entire pattern. Otherwise, you limit your derived classes by complicating
their implementation of the standard Dispose idiom. Follow the standard
Dispose idiom I've described. That will make life easier for you, for the
users of your class, and for those who create derived classes from your
types.
Item 18: Distinguish Between Value Types and Reference Types
Va l u e t y p e s o r r e f e r e n c e t y p e s ? S t r u c t s o r c l a s s e s ? Wh e n s h o u l d y o u u s e
each? This isn't C++, in which you define all types as value types and can
create references to them. This isn't Java, in which everything is a refer-
ence type (unless you are one of the language designers). You must decide
how all instances of your type will behave when you create it. It's an impor-
tant decision to get right the first time. You must live with the conse-
quences of your decision because changing later can cause quite a bit of
code to break in subtle ways. It's a simple matter of choosing the struct
 
 
Search WWH ::




Custom Search