C# Language Enum basics


Example

From MSDN:

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.

Essentially, an enum is a type that only allows a set of finite options, and each option corresponds to a number. By default, those numbers are increasing in the order the values are declared, starting from zero. For example, one could declare an enum for the days of the week:

public enum Day
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

That enum could be used like this:

// Define variables with values corresponding to specific days
Day myFavoriteDay = Day.Friday;
Day myLeastFavoriteDay = Day.Monday;

// Get the int that corresponds to myFavoriteDay
// Friday is number 4
int myFavoriteDayIndex = (int)myFavoriteDay;

// Get the day that represents number 5
Day dayFive = (Day)5;

By default the underlying type of each element in the enum is int, but byte, sbyte, short, ushort, uint, long and ulong can be used as well. If you use a type other than int, you must specify the type using a colon after the enum name:

public enum Day : byte 
{
    // same as before 
}

The numbers after the name are now bytes instead of integers. You could get the underlying type of the enum as follows:

Enum.GetUnderlyingType(typeof(Days)));

Output:

System.Byte

Demo: .NET fiddle