Enum
suggest changeIntroduction
An enum's underlying type can be byte, sbyte, short, ushort, int, uint, long, ulong, or char. The default is int, and it can be changed in the enum definition:
public enum Weekday : byte { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5 }
This is useful when P/Invoking to native code, mapping to data sources, and similar circumstances. In general, the default int should be used, because most developers expect an enum to be an int.
Syntax
- enum Colors { Red, Green, Blue } // Enum declaration
- enum Colors : byte { Red, Green, Blue } // Declaration with specific type
- enum Colors { Red = 23, Green = 45, Blue = 12 } // Declaration with defined values
- Colors.Red // Access an element of an Enum
- int value = (int)Colors.Red // Get the int value of an enum element
- Colors color = (Colors)intValue // Get an enum element from int
Remarks
An Enum (short for “enumerated type”) is a type consisting of a set of named constants, represented by a type-specific identifier.
Enums are most useful for representing concepts that have a (usually small) number of possible discrete values. For example, they can be used to represent a day of the week or a month of the year. They can also be used as flags, which can be combined or tested with bitwise operations.