In C# enum is a value type data type. The enum is used to declare a list of named integer constants. It can be defined using the enum keyword directly inside a namespace, class, or structure. The enum is used to give a name to each constant so that the constant integer can be referred using its name.
An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
enum is used to create numeric constants in .NET framework. All member of enum are of enum type. There must be a numeric value for each enum type.
The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
Declaring enum Variable
Syntax for declaring an enumeration is :
enum
{
enumeration list
};
Where enum_name specifies the enumeration type name and enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it. By default, the value of the first enumeration symbol is 0.
Example of enum is:
enum WeekDays
{
Monday = 0,
Tuesday =1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday =5,
Sunday = 6
}
How to get the value of enum:
An explicit cast is necessary to convert from enum type to an integral type. For example, to get the int value from an enum:
int dayNum = (int)WeekDays.Tuesday;
Some important points about enum:
1. enums are enumerated data type in c#.
2. enums are not for end-user, they are meant for developers.
3. enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same.
4. Enumerations (enums) make your code much more readable and understandable.
5. enum values are fixed. enum can be displayed as a string and processed as an integer.
6. The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
7. Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
8. Enums are value types and are created on the stack and not on the heap.