Jaa


Enumerting all values of an Enum

<to get all the values as an array see here

Screen shot Sometimes you need to do something in code and you hit on a simple solution, and then you sit back and marvel on the design that lets you do that. Sometime back when writing my blog on the usage of console color I needed to write some code that got all the values for the Enum ConsoleColor and print text using those colors. I used the following code.

 static void Main(string[] args){    ConsoleColor originalCol = Console.ForegroundColor;     foreach (ConsoleColor color inEnum.GetValues(typeof(ConsoleColor )))     {        Console.ForegroundColor = color;        Console.WriteLine("{0, -12} {1}", color, color.ToString(  "D"  ) );    }    Console.ForegroundColor = originalCol;}

All of this could be done so easily is because of the unified inheritance structure of .NET. All enums inherit from System.Enum and so a lot of functionality comes to you for free. You can use Enum.GetValues to do the work of getting all the values and use the base Enum types ToString overrides to give you correct string/value representations of the enum. Try doing this in C++ and the difference is evident.

The fact that I could do this so easily made me extremely happy. Programmers should be lazy and a language or framework that allows them to be lazy should be the platform of choice. As I had said in my profile I'm enjoying moving into C#/.NET from C++.

Comments

  • Anonymous
    January 15, 2006
    Something I would like to see in future .NET frameworks/CLR is the automatic overloading of the static members for enums.

    Instead of:

    KnownColor kc1 = (KnownColor)Enum.Parse(typeof(KnownColor), "BlanchedAlmond");
    KnownColor kc2 = (KnownColor)Enum.ToObject(typeof(KnownColor), 12);
    KnownColor[] values = (KnownColor[])Enum.GetValues(typeof(KnownColor));
    string name = Enum.GetName(typeof(KnownColor), KnownColor.BlanchedAlmond);
    string[] names = Enum.GetNames(typeof(KnownColor));

    you should write:

    KnownColor kc1 = KnownColor.Parse("BlanchedAlmond");
    KnownColor kc2 = KnownColor.ToObject(12);
    KnownColor[] values = KnownColor.GetValues();
    string name = KnownColor.GetName(KnownColor.BlanchedAlmond);
    string[] names = KnownColor.GetNames();

    // Dalle
  • Anonymous
    January 15, 2006
    Agreed, these would be nice additions. There should be no reason to remind users at every step that enums are inherited from System.Enum!!
  • Anonymous
    July 25, 2011
    Hi...... This solutions works only .net framework, it's not working for .net compact framework because Enum.GetValues () is not supported. Please give any solution that will work for  .net compact framework .