36

What is the best way to localize enumeration descriptions in .net?

(See Adding descriptions to enumeration constants for enum description example)

Ideally I would like something that uses ResourceManager and resource files so it fits in with how other areas of the app are localized.

0

8 Answers 8

26

This is what I ended up going with, I didn't see the value in adding a custom attribute class to hold a resource key and then looking up into the resource files - why not just use the enums typename + value as a resource key?

using System;
using System.Resources;
using System.Reflection;

public class MyClass
{
  enum SomeEnum {Small,Large};

  private ResourceManager _resources = new ResourceManager("MyClass.myResources",
                          System.Reflection.Assembly.GetExecutingAssembly());    

  public string EnumDescription(Enum enumerator)
  {     
    string rk = String.Format("{0}.{1}",enumerator.GetType(),enumerator);
    string localizedDescription = _resources.GetString(rk);

    if (localizedDescription == null)
       {
       // A localized string was not found so you can either just return
       // the enums value - most likely readable and a good fallback.
       return enumerator.ToString();

       // Or you can return the full resourceKey which will be helpful when
       // editing the resource files(e.g. MyClass+SomeEnum.Small) 
       // return resourceKey;
       }
    else
       return localizedDescription;
    }


  void SomeRoutine()
  {
    // Looks in resource file for a string matching the key
    // "MyClass+SomeEnum.Large"
    string s1 = EnumDescription(SomeEnum.Large);       
  }
}
4
  • 4
    an Enum is not an enumerator, is it? It's an enumerated type, but an enumerator is something quite different I believe...
    – Svish
    Jul 13, 2009 at 6:39
  • 4
    Using C# 3.5 you can make that method an extension method so that you can then use SomeEnum.Large.EnumDescription(); Aug 25, 2009 at 23:08
  • 2
    Just stumbled upon this question when searching for another issue. I'd only remind that using type and member names makes your application more difficult to obfuscate (you must exclude the sensible declaration from the process). May 7, 2010 at 7:15
  • @Ryan How can I adapt this code to use it on Enum.GetValues(typeof(SomeEnum))? I'd like to be able to use my enums as DataSource
    – Diego
    Nov 18, 2011 at 21:21
24

My solution, using native decription attribute:

public class LocalizedEnumAttribute : DescriptionAttribute
{
    private PropertyInfo _nameProperty;
    private Type _resourceType;

    public LocalizedEnumAttribute(string displayNameKey)
        : base(displayNameKey)
    {

    }

    public Type NameResourceType
    {
        get
        {
            return _resourceType;
        }
        set
        {
            _resourceType = value;

            _nameProperty = _resourceType.GetProperty(this.Description, BindingFlags.Static | BindingFlags.Public);
        }
    }

    public override string Description
    {
        get
        {
            //check if nameProperty is null and return original display name value
            if (_nameProperty == null)
            {
                return base.Description;
            }

            return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);
        }
    }
}

public static class EnumExtender
{
    public static string GetLocalizedDescription(this Enum @enum)
    {
        if (@enum == null)
            return null;

        string description = @enum.ToString();

        FieldInfo fieldInfo = @enum.GetType().GetField(description);
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes.Any())
            return attributes[0].Description;

        return description;
    }
}

The Enum declaration

public enum MyEnum
{
    [LocalizedEnum("ResourceName", NameResourceType = typeof(ResourceType))]
    Test = 0
}

Then call MyEnumInstance.GetLocalizedDescription()

3
  • Needs BindingFlags.NonPublic and needs to access base.Description within NameResourceType.set. See my answer for flags enum support.
    – kerem
    Nov 12, 2012 at 9:26
  • This seems much more reusable to me then the other solution. Thanks
    – Peter
    Jul 26, 2013 at 13:16
  • I had to change NameResourceType to typeof(Resource) to get this working. Thanks!
    – pizycki
    Oct 21, 2014 at 15:20
8

there is an easy solution: use LocalizedDescription attribute to pass a resource key.

    [Serializable]
    public class LocalizableDescriptionAttribute:DescriptionAttribute
    {
        public LocalizableDescriptionAttribute(string resourceKey)
            :base(Resources.ResourceManager.GetString(resourceKey))
        { }

    }
4
  • I am not sure what this gets you over using the enums full type name (namespace.enumname.value) as the resourceKey. It seems like an extra unnecessary step (using reflection to get the LocalizableDescriptionAttribute) over just going to the resourceManager - what am I missing?
    – Ryan
    Feb 20, 2009 at 13:59
  • I think we have a misunderstanding. I use my attribute to localize enum values description. I guess you're talking about localizing enums but not their values.
    – Valentin V
    Feb 20, 2009 at 14:39
  • You can't decorate enum value with Description attribute and pass a resource key.
    – Valentin V
    Feb 20, 2009 at 14:41
  • Nope - I want to leave the enum values the same, just localize a description. My own answer below may make my comment clearer. (BTW - ignore where I said reflection, I should have said LocalizableDescriptionAttribute.GetCustomAttribute)
    – Ryan
    Feb 20, 2009 at 22:56
4

One way I did it once, was to add an extention method in the same namespace as an enum, which returned a string. In my case it was just hardcoded, but would be no problem getting them from a resource file.

    public static string Describe(this SomeEnum e)
    {
        switch(e)
        {
            SomeEnum.A:
                return "Some text from resourcefile";
            SomeEnum.B:
                return "Some other text from resourcefile";
            ...:
                return ...;
        }
    }

Maybe not an extremly smooth or fancy solution, but it works =)

2
  • + 1 for using an extension method...though I would prefer to use the enum's fully qualified type name as the resource key (see Ryans answer) Apr 16, 2010 at 9:57
  • @SDX2000: Yeah, that could be a very nice alternative way of getting the strings.
    – Svish
    Apr 16, 2010 at 10:36
1

Replace @nairik's method with the following to add support for flags enums.

public static string GetLocalizedDescription(this Enum @enum)
{
    if ( @enum == null )
        return null;

    StringBuilder sbRet = new StringBuilder();

    string description = @enum.ToString();

    var fields = description.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

    foreach ( var field in fields )
    {
        FieldInfo fieldInfo = @enum.GetType().GetField(field);
        DescriptionAttribute[] attributes = ( DescriptionAttribute[] )fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if ( attributes.Any() )
            sbRet.AppendFormat("{0}, ", attributes[0].Description);
        else
            sbRet.AppendFormat("{0}, ", field);
    }

    if ( sbRet.Length > 2 )
        sbRet.Remove(sbRet.Length - 2, 2);

    return sbRet.ToString();
}

and replace NameResourceType in the attribute:

public Type NameResourceType
{
    get
    {
        return _resourceType;
    }
    set
    {
        _resourceType = value;

        _nameProperty = _resourceType.GetProperty(base.Description, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
    }
}
0

See my table example in this question:

Localisation/I18n of database data in LINQ to SQL

The status type table maps to Enumeration values. The real benefit here is that you can have localisation in your reports and across your applications, and specify external IDs for integration with 3rd parties who don't want your internal values etc. It decouples the enum description from it's value.

1
  • Nice method for db centric apps, but really overkill for my needs.
    – Ryan
    Feb 20, 2009 at 13:53
0

You can't have multiple System.ComponentModel.DescriptionAttribute applied (so that option is out).

So add a level of indirection, the description holds a resource name, and then use the localisation support in resources. Clearly users of the enum will need to call your helper method to do this.

1
  • This is what Valentin Vasiliev proposes but without the need to use a helper method - the same comment applies too.
    – Ryan
    Feb 20, 2009 at 13:55
0

This looks good: http://www.codeproject.com/Articles/19980/Data-Binding-an-Enum-with-Descriptions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.