Skip to content

Instantly share code, notes, and snippets.

@swoker
Created May 25, 2011 16:24
Show Gist options
  • Save swoker/991292 to your computer and use it in GitHub Desktop.
Save swoker/991292 to your computer and use it in GitHub Desktop.
C#: Loop an Enum with Description Strings
using System;
using System.ComponentModel;
using System.Reflection;
namespace EnumLoopExample
{
class Program
{
enum Car
{
[Description("Bayerische Motoren Werke Aktiengesellschaft (BMW AG)")]
BMW = 0,
[Description("Mercedes-Benz (Daimler AG)")]
MERCEDES = 5,
[Description("Audi AG")]
AUDI = 10
}
static string StringValueOfEnum(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
static void Main(string[] args)
{
foreach (Car car in Enum.GetValues(typeof(Car)))
{
Console.WriteLine(String.Format("{0} has value {1}", StringValueOfEnum(car), (int)car));
}
// output will be:
// Bayerische Motoren Werke Aktiengesellschaft (BMW AG) has value 0
// Mercedes-Benz (Daimler AG) has value 5
// Audi AG has value 10
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment