Chapter 4. Enumerations

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 colors red, blue, and yellow could be defined by the enumeration ValidShapeColor ; likewise square, circle, and triangle could be defined by the enumeration ValidShape . These enumerations would look like the following:

 enum ValidShapeColor {     Red, Blue, Yellow } enum ValidShape {     square = 2, circle = 4, triangle = 6 } 

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 ValidShapeColor enumeration previously defined would be exactly the same if it were defined in the following manner:

 enum ValidShapeColor {     Red = 0, Blue = 1, Yellow = 2 } 

Enumerations are good code-documenting tools. For example, it is more intuitive to write the following:

 ValidShapeColor currentColor = ValidShapeColor.Red; 

than it is to write:

 int currentColor = 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.



C# Cookbook
C# 3.0 Cookbook
ISBN: 059651610X
EAN: 2147483647
Year: 2003
Pages: 315

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net