Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to provide localization for Enums?

I'm writting a multi-lingual application that uses many enums, and I'd like to achieve the following objectives:

  1. Display Enum names as localized strings
  2. Provide localized descriptions using attributes
  3. Enable language sensitive parsing of enums back to int values

I'm keen to to decorate the enum using attributes + a resource file, such that the localized strings can be reached from run-time type info. I've been down the route before of declaring a static class with static members instead of an enum, but this presented as many problems as it solved.

Is some sort of a TypeDescriptor based mechanism appropriate? Or even possible?

Moreover - how does one accomplish goal #3 in a clean, generic, re-usable manner?


Since asking this question, I've completed the open source library that needed localizable enum displays. I went with the technique of implementing TypeConverters. Full source available at http://measures.codeplex.com/

like image 254
Mark Avatar asked Oct 12 '10 12:10

Mark


3 Answers

How about writing TypeConvertor for your enums?

  1. Define some custom attribute that will identify resource string for enum value.
  2. Write TypeConvertor that will look up this attribute to get resource id and then convert the value to string. (You can have helper class for the same but using TypeConvertor and TypeConvertorAttribute allows to use it more transparently).
  3. You can write a generic class/method that will do reverse conversion (from string to enum). The method will be something like Parse<T>(string value) where T will be enum type. The implementation will build (on demand) a lookup dictionary for given enum type T using reflection to look up for your custom attribute.
like image 112
VinayC Avatar answered Sep 28 '22 00:09

VinayC


I just wrote an answer to another thread touching on some of the stuff. Look here for some code samples.

like image 30
danijels Avatar answered Sep 28 '22 00:09

danijels


I think you are in the exactly right direction — use attributes to decorate the enumeration members. The only think you probably need to do is forget about System.ComponentModel and design your own set of attributes that will respect your requirements and overall application architecture.

We used the same approach and it works as expected “in a clean, generic, re-usable manner”. The only aspect we didn't implemented because we didn't need it was actual internationalization. However, that's just some mechanics that requires you to keep track of the current culture and decide where to select resource files. Basically, you might need to select between “multiple attributes” (one per language) or “single attribute” (one for all languages encapsulating resource file selection) approach.

like image 29
Ondrej Tucny Avatar answered Sep 28 '22 00:09

Ondrej Tucny