| Enumerators can be used to store lists of value types with set values,
much like constants. For example, a C# constant could be defined using the statement
below: const int EngineCapacity = 1000;
If there was more than one engine capacity, then a range of constants could be defined,
such as:
const int EngineCapacitySmall = 600;
const int
EngineCapacityMedium = 1000;
const int
EngineCapacityLarge = 1200;
const int
EngineCapacityExtraLarge = 1800;
If even more constants were needed then this list could get pretty large, so it
would be more convenient to group them into a single enumerator, by using syntax such as
that shown below:
/// <summary>
/// Engine capacity enumerator
/// </summary>
enum EngineCapacity : int
{
Small = 600,
Medium = 1000,
Large = 1200,
ExtraLarge = 1800
}
Each enumerator is assigned a name (in this case it is EngineCapacity)
and an optional data type. Here, the EngineCapacity enumerator is assigned a type of int,
although being the default data type for enumerators it does not need to be specified -
the following code will also work:
enum EngineCapacity : int
{
Small = 600,
Medium = 1000,
Large = 1200,
ExtraLarge = 1800
}
A value for the enumerator's type does not need to be specified - if it
is not then the value of a type is incremented by one from the previous type (taking 0 as
the first value). So in the example below, the small engine capacity will be 0 and the
large engine capacity value will be 1001:
enum EngineCapacity : int
{
Small,
Medium = 1000,
Large,
ExtraLarge = 1800
}
Using the enumerator
Once the enumerator has been assigned it may be used in instances such as that shown
below:
int RequiredCapacity = 1000;
if
(RequiredCapacity == (int) EngineCapacity.ExtraLarge)
{
//Check customer has
the required maintenance contract
//for the
largest engine type
if
(CheckCustomerHasMaintenenceContract() == false)
{
return;
}
}
Note that Visual Studio understands enumerators, and will usefully include their
value types in the intellisense for that enumerator.
|