Enumerations implicitly inherit from System.Enum, which, in turn, inherits from System.ValueType. Enumerations have a single use: to describe items of a specific group. For example, the traffic light colors red, yellow, and green could be defined by the enumeration TrafficLight; likewise Low, Medium, and High could be defined by the enumeration RiskLevel. These enumerations would look like the following:
enum TrafficLight { Red, Yellow, Green } enum RiskLevel { Low = 0, Medium = 2, High = 4 }
Each item in the enumeration receives a numeric value regardless of whether you assign one. Since the compiler automatically adds the numbers starting with zero and increments by one for each item in the enumeration, the TrafficLight enumeration previously defined would be exactly the same if it were defined in the following manner:
enum TrafficLight
{
Red = 0, Yellow = 1, Green = 2
}
Enumerations are good code-documenting tools. For example, it is more intuitive to write the following:
TrafficLight currentState = TrafficLight.Green;
than it is to write:
int currentState = 0;
Either mechanism can work, but the first method is easy to read and understand, especially for a new developer taking over someone else’s code.
Popularity: 3% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply