Information Technology Reference
In-Depth Information
public enum
Planet2
{
None =
0
,
Mercury =
1
,
Venus =
2
,
Earth =
3
,
Mars =
4
,
Jupiter =
5
,
Saturn =
6
,
Neptune =
7
,
Uranus =
8
}
Planet
sphere =
new
Planet
();
sphere now contains a value for None. Adding this uninitialized default to
the Planet
enum
ripples up to the ObservationData structure. Newly cre-
ated ObservationData objects have a 0 magnitude and None for the target.
Add an explicit constructor to let users of your type initialize all the fields
explicitly:
public struct
ObservationData
{
Planet
whichPlanet;
//what am I looking at?
double
magnitude;
// perceived brightness.
ObservationData(
Planet
target,
double
mag)
{
whichPlanet = target;
magnitude = mag;
}
}
But remember that the default constructor is still visible and part of the
structure. Users can still create the system-initialized variant, and you can't
stop them.
This is still somewhat faulty, because observing nothing doesn't really
make sense. You could solve this specific case by changing Observation-
Data to a class, which means that the parameterless constructor does not