Wednesday, March 24, 2010

Using .NET Methods with enums

If we have an enum like this one:
enum Color { Red = 1, Green, Blue };
We can declare a blue color object using the following statement:
Color c = Color.Blue;
We can display the name of this element simply by using the ToString method like this:
Console.WriteLine( c );
This statement displays the string Blue.
We can also use the methods of the System.Enum structure. This structure includes various methods to process enums. One useful method, which is used to display the name of any enum element, is GetName. If we declare a general Color object like this:
Color c = new Color();
We can use this method to display a specific element by using its numeric value. For example, we can display the name of the element whose value is 2 by using the following statement:
Console.WriteLine(Enum.GetName(c.GetType(),2));
This statement displays the string Green.
Another useful method is GetNames. It stores the names of the enum elements in a string array. For example, we can store all the Color names in an array like this:
string[] colorNames = Enum.GetNames(c.GetType());
We can then display this array by using a repetition loop.
These methods are demonstrated in the following example.
//Example 7-5.cs
//Using System.Enum methods
using System;
//Declare the Color enum:
enum Color { Red = 1, Green, Blue }
class MyClass
{
    static void Main()
    {
        //Declare a blue color object:
        Color myColor = Color.Blue;
        //Display the color name using ToString:
        Console.WriteLine(“My color is: {0}”, myColor);     //Blue

        //Declare a color object:
        Color yourColor = new Color();
        //Display the color whose value is 2 by using the GetName method:
        Console.WriteLine(“Your color is : {0}” , Enum.GetName(yourColor.GetType(), 2));    //Green
        //Display all the color names using the GetNames method:
        Console.WriteLine(“Your colors are: “);
        //Declare a string array for colors:
        string[] colorNames = Enum.GetNames(yourColor.GetType());
        foreach(string s in colorNames)
            Console.WriteLine(“{0}”, s);
    }
}

No comments:

Post a Comment