.NET TRANSLATING AN ENUM IN C# USING THE DESCRIPTION ATTRIBUTE
-
It’s always a good idea to use enumerations for properties that have a limited set of valid values, rather than a number. This allows your code to check whether you’re assigning a valid value to the property, and the individual values have easy-to-read names. However, the names you use cannot contain spaces or other non-alphabet characters, and are limited to the English language (you cannot use characters like á, õ etc.)
Suppose you have the following enumeration:
public enum EventType
{
Workshop,
Debate,
Lecture,
Conference
}
In order to add human-readable names, possibly in another language, you could add description attributes:
public enum EventType
{
[Description("Workshop")]
Workshop,
[Description("Mesa redonda/Debate")]
Debate,
[Description("Palestra")]
Lecture,
[Description("Conferência")]
Conference
}
Now, here’s how to access these descriptions in your code:
public class EnumTools
{
public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
}
Usage:
EventType type = EventType.Conference;
EnumTools.GetDescription(type);