How to use Enum in C#
If you have a number of constants that are logically related to each other, then you can group together these constants in an enumeration.
Enum declaration :
Enums are strongly typed constants which makes the code more readable and less prone to errors. It is useful when you have a set of values that are functionally significant and unchanged. The main advantage of Enum is make it easy to change values in the future, also you can reduces errors caused by transposing or mistyping numbers.
Retrieve and check the Enum value
A simple example
By default the underlying type of each element in the enum is int. If you try with above example to convert to integer then yo can see the result like the following:
Output is : Temperature value is..1
You can specify another integral numeric type by using a colon. The following Enum declare as byte, you can verify the underlying numeric values by casting to the underlying type.
You can retrieve the value like the following:
You can assign any values to the elements in the enumerator list of an enumeration type. By default, the first member of an enum takes the value of zero. If this value doesn't make sense for your enum, you can change it to one or some other number. If you declare a different value in the first member of Enum then it assign the next value greater by one than that of the immediately preceding member
Output is : Temperature value is.. 3
How to get int value from enum
How can an int value cast to enum ?
Followoing is the easiest method to cast an int to enum.
MyEnum myenum = (MyEnum)intvalue;
Converts int to enum values
MyEnum myenum = (MyEnum)Enum.ToObject(typeof(MyEnum) , intvalue);
You can check if it's in range using Enum.IsDefined
Enum.Parse() converts the C# string representation of the name or integer value of one or more enumerated constants to an equivalent Enum object.
String convert to Enum
Output is : green
How to Loop through all enum values
The C# GetValues method returns an array that contains a value for each member of the enum Type . If more than one members have the same value, it returned array includes duplicate values
Iterating through an enum
The following example will show how do enumerate an enum .
Enum Flags Attribute
The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. More about.... Enum Flags Explained
Convert an enum to a List
The following program shows how to convert an enum to List Datastructure. More about.... Enum to List
Enum in Switch Case
The following program shows how to use Enum in Switch..Case statement.