C# offers another way to group data: an enumeration. This allows the developer to establish a set of values for an instance of the group. Any single instance of an enumeration can have only a value that is defined within the group.
The compiler automatically assigns each member of the enumeration an integer value. The first member is always assigned a zero, followed by a one. However, you can start the sequence with any integer value you choose by explicitly setting the value of the member.
The names used for enumerations must be distinct from those of other identifiers. After you have defined an enumeration, the name of the enumeration is used to declare an instance of the enumeration. In the following example, MyWeek is an instance of the enum DaysOfWeek. This example also shows how to make an enum start with a value other than zero by assigning values to each member.
public enum Months
{
January = 1,
February = 2,
March = 3
}
You can also use an enum to define bit flags by using the [Flags] attribute, as in this example:
[Flags] enum MyBits
{
On = 1,
Off = 2,
Broken = 4
}
The following example demonstrates the use of enum.
using System; namespace Client.Chapter_3___Structs__Enums__Arrays_and_Collections { //Defines an enum enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } class Enums { static void Main(string[] args) { //Declares an instance of the enum DaysOfWeek Today = DaysOfWeek.Monday; //Prints Monday Console.WriteLine(Today); } } }