How to get C# Enum description from value?
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.
Update
The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.
In Enums.NET you'd use:
string description = ((MyEnum)value).AsString(EnumFormat.Description);
Original post
I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:
string description = Enums.GetDescription((MyEnum)value);
This:
- Ensures (with generic type constraints) that the value really is an enum value
- Avoids the boxing in your current solution
- Caches all the descriptions to avoid using reflection on every call
- Has a bunch of other methods, including the ability to parse the value from the description
I realise the core answer was just the cast from an int
to MyEnum
, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)
I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:
public static string DescriptionAttr<T>(this T source)
{
FieldInfo fi = source.GetType().GetField(source.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) return attributes[0].Description;
else return source.ToString();
}
Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:
string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();