Localizing Enum Description

December 18, 2009 08:26 by Anton

Recently, I ran into a problem , where I need to iterate through an enum, and get a localized description of its member. As an example, I’ll use enum Faculties.

public enum Faculties
{
    Engineeering=1,
    Economy=2,
    Physchology=3,
    Law=4,
    Pharmacy=5
}

Since we’re doing localization we need to create resx file and localized resx (in this example I use Indonesian culture), and assign value for each enum member. Don’t forget to set resource access modifier to public.

enum_neutral

enum_localized

How do we connect enum member with resource file? We can use a DescriptionAttribute and add it to all enum members. The trick here is we set the description to strongly type property name .

So here is our final enum:

public enum Faculties
{
    [Description("Faculties_Engineering")]
    Engineering = 1,

    [Description("Faculties_Economy")]
    Economy = 2,
        
    [Description("Faculties_Physchology")]
    Physchology = 3,
        
    [Description("Faculties_Law")]
    Law = 4,
        
    [Description("Faculties_Pharmacy")]
    Pharmacy = 5
}

And finally we add extension method for Faculties enum

public static class Extensions
{
    public static string ToLocalizedString(this Faculties val)
    {
         DescriptionAttribute[] attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
         string description = attributes.Length > 0 ? attributes[0].Description : string.Empty;
         string result = string.Empty;
         if (!string.IsNullOrEmpty(description))
         {
             result = typeof(LanguageResource).GetProperty(description).GetValue(null, null) as string;
         }
         return result;
    }
} 

Here is the output of iterating Faculties enum in Indonesian culture:

console_enum

LocalizedEnum.7z (7.12 kb)


Add comment




  Country flag

Click to change captcha
biuquote
  • Comment
  • Preview
Loading