Created
May 25, 2011 16:24
-
-
Save swoker/991292 to your computer and use it in GitHub Desktop.
C#: Loop an Enum with Description Strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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