Information Technology Reference
In-Depth Information
// Default starts at 0 otherwise.
Mercury =
1
,
Venus =
2
,
Earth =
3
,
Mars =
4
,
Jupiter =
5
,
Saturn =
6
,
Neptune =
7
,
Uranus =
8
// First edition included Pluto.
}
Planet
sphere =
new
Planet
();
sphere is 0, which is not a valid value. Any code that relies on the (nor-
mal) fact that
enums
are restricted to the defined set of enumerated values
won't work. When you create your own values for an
enum
, make sure that
0 is one of them. If you use bit patterns in your
enum
, define 0 to be the
absence of all the other properties.
As it stands now, you force all users to explicitly initialize the value:
Planet
sphere2
=
Planet
.Mars;
That makes it harder to build other value types that contain this type:
public struct
ObservationData
{
private
Planet
whichPlanet;
//what am I looking at?
private double
magnitude;
// perceived brightness.
}
Users who create a new ObservationData object will create an invalid
Planet field:
ObservationData
d =
new
ObservationData
();
The newly created ObservationData has a 0 magnitude, which is reason-
able. But the planet is invalid. You need to make 0 a valid state. If possible,
pick the best default as the value 0. The Planet
enum
does not have an obvi-
ous default. It doesn't make any sense to pick some arbitrary planet when-
ever the user does not. If you run into that situation, use the 0 case for an
uninitialized value that can be updated later: