Enums are special value types that lets you specify a group of numeric constants. For example:
enum Languages
{
English,
Spanish,
Chinese,
Japanese,
French,
Filipino
}
We can use an anum as follows:
Languages ls = Languages.Filipino
bool canSpeakFilipino (ls == Languages.Filipino) //return true
By default enums have an underlying ingtegral value which is of type int and the constant values start from 0 to infinity based on how they enum members are declared. You can also specify an alternate integral type as follows
enum Languages: byte
{
English,
Spanish,
Chinese,
Japanese,
French,
Filipino
}
Or do an explicit value for each enum member
enum Languages: byte
{
English = 1,
Spanish = 2,
Chinese = 4,
Japanese = 8,
French = 16,
Filipino = 32
}
You can also assign some values of the enum and let the compiler decide on the value of the other unassigned enum members which is an increment of 1 by the previous value of the previous member.
enum Languages
{
English = 1,
Spanish,
Chinese,
Japanese = 8,
French,
Filipino
}
The code above will result to English = 1, Spanish = 2, Chinese = 3, Japanese = 8, French = 9, Filipino = 10
It is a good practice to define a value for 0 in enums to signify "no value" as 0 in enums mean the absence of all properties possible. Defining a value for 0 with make it a valid state for your enum.
enum Languages: byte
{
None = 0,
English = 1,
Spanish = 2,
Chinese = 4,
Japanese = 8,
French = 16,
Filipino = 32
}
This is specifically useful when you are using flags attribute on your enum as this will catch values presented as 0
[Flags]
enum Languages: byte
{
None = 0,
English = 1,
Spanish = 2,
Chinese = 4,
Japanese = 8,
French = 16,
Filipino = 32
}
Language ls; //will default to 0
Console.WriteLine(ls); //will print None on the console
Adding the [Flags] attribute to your enums will help you "combine values" of enums into one.
Language ls = Language.English | Language.Filipino | Language.French;
Console.WriteLine("I can speak {0}", ls);
//The code above will print: I can speak English, Filipino, French