views:

101

answers:

3

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/

+2  A: 

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

danijels
I have something very similar to what you posted already, but it doesn't take care of the localization aspect of using enums. Do you have any answers around localization?
Mark
+2  A: 

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.

Ondrej Tucny
Got any sample code you can post here?
Mark
+2  A: 

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.
VinayC
Seems to be the right way to go... got any example code?
Mark
Sorry Mark - don't have any example code!
VinayC