<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 in Enum.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++.