C# Tutorial - Application 11 – Enumerating ConstantsWhen you have a group of related constants, you may wish to combine them into an enumeration. An enumeration is a value type defined at compile time that groups related constants. All of the constants must be of the same type. Create a new console Application called App11. We are going to create a simple application that displays the contents of an enumeration. Add the following code: class Program
{
enum Marks
{
Pass = 40,
Merit = 65,
Distinction = 85
}
static void Main(string[] args)
{
Console.WriteLine("The {0} mark is {1}", Marks.Pass,
(int)Marks.Pass);
Console.WriteLine("The {0} mark is {1}", Marks.Merit,
(int)Marks.Merit);
Console.WriteLine("The {0} mark is {1}", Marks.Distinction,
(int)Marks.Distinction);
}
}
Which gives the output: The Pass mark is 40 The Merit mark is 65 The Distinction mark is 85 We accessed the enumeration Marks twice in each WriteLine statement.
We could, if we wanted to, compare a number with the associated value of any of the constants. For example: if( _assignment < (int)Marks.Pass )
Console.WriteLine("You failed the assignment");
else
Console.WriteLine("You passed the assignment");
EnumerationsAn enumeration contains a related group of constants of the same type, which must be byte, sbyte, short, ushort, int, uint, long or ulong. An enumeration takes the following form: enum-modifiers enum identifier : enum-base
{
enum-body
}
Where:
When declaring an enumeration, if you do not assign any values to the constants, then they will automatically be assigned values starting at zero and incrementing by one for each constant. Similarly if you give the first constant a value, then each constant thereafter will increment by one. In the following example, Spring is assigned the value 1 and the other values become those shown in the comments. enum Seasons
{
Spring = 1,
Summer, // 2
Autumn, // 3
Winter // 4
}
When using an enumeration, you must call the enumeration before the element of the enumeration that you require. This is because the constants are contained within the scope of the enumeration and mean nothing outside of it on their own. This allows different enumerations to contain the same names without naming collisions.
|