I have an enum with Description attributes like this:
public enum MyEnum { Name1 = 1, [Description("Here is another")] HereIsAnother = 2, [Description("Last one")] LastOne = 3 }
I found this bit of code for retrieving the description based on an Enum
public static string GetEnumDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; if (attributes != null && attributes.Any()) { return attributes.First().Description; } return value.ToString(); }
This allows me to write code like:
var myEnumDescriptions = from MyEnum n in Enum.GetValues(typeof(MyEnum)) select new { ID = (int)n, Name = Enumerations.GetEnumDescription(n) };
What I want to do is if I know the enum value (e.g. 1) - how can I retrieve the description? In other words, how can I convert an integer into an "Enum value" to pass to my GetDescription method?
%s is for string %d is for decimal (or int) %c is for character.
int value = 1; string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With