This is not a beginners tutorial for concept of Enum. Its is assumed that you are aware of the basic concepts of enum. Here I am presenting few advance level tricks and tips which programmers often need while working with enums. For basic tutorial on enum you can visit The C# Station Tutorial (Lesson 17: Enums) or msdn at http://msdn.microsoft.com/en-us/library/sbbt4032(VS.80).aspx
All enum instances in .net implicitly inherit the System.Enum type in the Base Class Library and hence we can use members of System.Enum with the instances of enums. There are few good functionalities available in System.Enum which are often required while working with enums and for manipulating them. So lets have look on them one by one.
One of the common requirement is to cast the enum object to and fro between its integer and string values. Consider following sample code:
1: public enum ColorSwatch
2: {
3: Black = 0,
4: Red = 1,
5: Green = 2,
6: Blue = 3,
7: Yellow = 4,
8: Orange = 5,
9: Pink = 6
10: }
ColorSwatch selectedColor = (ColorSwatch)colorCode;
c = (ColorSwatch )Enum.ToObject(typeof(ColorSwatch ), colorCode)
int c = (int)cs;
As per this code, integer variable c should now have integer value associated with Orange.
bool ignoreCase = true;
ColorSwatch CC = (ColorSwatch)Enum.Parse(typeof(ColorSwatch),
colorStr, ignoreCase);
{
ColorSwatch CC = (ColorSwatch)Enum.Parse(typeof(ColorSwatch),
colorStr, ignoreCase);
}
Below are few other important functionalities available under System.Enum which are often useful :
- Enum.GetName() :
- Enum.GetNames() :
Retrieves an array of string of the names of the constants in a specified enumeration. The elements of the return value array are sorted by the values of the enumerated constants.
- Enum.GetValues() :
Retrieves an array of the values of the constants in a specified enumeration.
Retrieves the name(string) of the constant in the specified enumeration that has the specified value.
0 comments
Posts a comment