Information Technology Reference
In-Depth Information
modify text data before you construct an immutable string object. Use
StringBuilder to create the final version of a string object. More impor-
tantly, learn from that design idiom. When your designs call for immutable
types (see Item 20), consider creating builder objects to facilitate the multi-
phase construction of the final object. That provides a way for users of
your class to construct an object in steps, yet maintain the immutability of
your type.
The Garbage Collector does an efficient job of managing the memory that
your application uses. But remember that creating and destroying heap
objects still takes time. Avoid creating excessive objects; don't create what
you don't need. Also avoid creating multiple objects of reference types in
local functions. Instead, consider promoting local variables to member
variables, or create static objects of the most common instances of your
types. Finally, consider creating mutable builder classes for immutable
types.
Item 17: Implement the Standard Dispose Pattern
We ' v e d i s c u s s e d t h e i m p o r t a n c e o f d i s p o s i n g o f o b j e c t s t h a t h o l d u n m a n -
aged resources. Now it's time to cover how to write your own resource-
management code when you create types that contain resources other than
memory. A standard pattern is used throughout the .NET Framework for
disposing of unmanaged resources. The users of your type will expect you
to follow this standard pattern. The standard dispose idiom frees your
unmanaged resources using the IDisposable interface when clients remem-
ber, and it uses the finalizer defensively when clients forget. It works with
the Garbage Collector to ensure that your objects pay the performance
penalty associated with finalizers only when necessary. This is the right way
to handle unmanaged resources, so it pays to understand it thoroughly.
The root base class in the class hierarchy should implement the IDisposable
interface to free resources. This type should also add a finalizer as a defen-
sive mechanism. Both of these routines delegate the work of freeing
resources to a virtual method that derived classes can override for their
own resource-management needs. The derived classes need to override the
virtual method only when the derived class must free its own resources
and it must remember to call the base class version of the function.
To b e g i n , y o u r c l a s s m u s t h a v e a fi n a l i z e r i f i t u s e s u n m a n a g e d r e s o u r c e s .
Yo u s h o u l d n o t r e l y o n c l i e n t s t o a l w a y s c a l l t h e D i s p o s e ( ) m e t h o d . Yo u ' l l
 
 
Search WWH ::




Custom Search