Enumerations in C# are used to hold collection of values where each value corresponds to an integer.
MSDN defines enum as: An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.
This might seem complex at the beginning but the concept is quite simple. Consider a scenario where you want to store months in a year and you want to make sure that when you write January, you get integer 1; similarly for February you get 2. In such cases, enumerations can be very handy. Have a look at the following example.
using System;
namespace CSharpTutorials {
enum months { Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov, Dec };
class Tutorial {
static void Main(string[] args) {
months monthofyear;
monthofyear = months.Apr;
int firstmonth = (int)months.Jan;
int lastmonth = (int)months.Dec;
Console.WriteLine("January is the: {0} month.", firstmonth+1);
Console.WriteLine("December is the: {0} month.", lastmonth+1);
Console.ReadKey();
}
}
}
Enumeration variable can only contain one of the values of the enumeration. In the above code monthofyear variable of enumeration of type months have been defined and the month of Apr has been assigned to it.
Like arrays, enumerations follow zero based index which means that the integer value for first item is zero and for last item is k-1 where k is the size of the enumeration. Therefore, you need to add one to the integer value of enumeration item, in order to get actual associated integer value of the enumeration.
Few other facts about C# enums: