Information Technology Reference
In-Depth Information
There is less heap fragmentation, less garbage, and less indirection. More
important, value types are copied when they are returned from methods
or properties. There is no danger of exposing references to internal struc-
tures. But you pay in terms of features. Value types have very limited sup-
port for common object-oriented techniques. You cannot create object
hierarchies of value types. You should consider all value types as though
they were sealed. You can create value types that implement interfaces but
require boxing, which Item 17 shows causes performance degradation.
Think of value types as storage containers, not objects in the OO sense.
Yo u ' l l c r e a t e m o r e r e f e r e n c e t y p e s t h a n v a l u e t y p e s . I f y o u a n s w e r y e s t o a l l
these questions, you should create a value type. Compare these to the pre-
vious Employee example:
1. Is this type's principal responsibility data storage?
2. Is its public interface defined entirely by properties that access its data
members?
3. Am I confident that this type will never have subclasses?
4. Am I confident that this type will never be treated polymorphically?
Build low-level data storage types as value types. Build the behavior of
your application using reference types. You get the safety of copying data
that gets exported from your class objects. You get the memory usage ben-
efits that come with stack-based and inline value storage, and you can uti-
lize standard object-oriented techniques to create the logic of your
application. When in doubt about the expected use, use a reference type.
Item 19: Ensure That 0 Is a Valid State for Value Types
The default .NET system initialization sets all objects to all 0s. There is no
way for you to prevent other programmers from creating an instance of a
value type that is initialized to all 0s. Make that the default value for your
type.
One special case is enums . Never create an enum that does not include 0 as
a valid choice. All enums are derived from System.ValueType. The values
for the enumeration start at 0, but you can modify that behavior:
public enum Planet
{
// Explicitly assign values.
 
 
Search WWH ::




Custom Search