views:

1784

answers:

2

I'm trying to understand how to use Type Converters after reading this answer to one of my other questions. But I'm not sure if I quite get it...

In my particular case I would like to "convert" an enum member into a localized string by getting a resource string depending on what enum member it is. So for example if I had this enum:

public enum Severity
{
    Critical,
    High,
    Medium,
    Low
}

or this:

public enum Color
{
    Black = 0x0,
    Red = 0x1,
    Green = 0x2,
    Blue = 0x4,
    Cyan = Green | Blue,
    Magenta = Red | Blue,
    Yellow = Red | Green,
    White = Red | Green | Blue,
}

How would I create a Type Converter that could convert those members into localized strings? And how would I use it? Currently I would need to use it in a WinForms application, but more general examples are welcome as well.

+2  A: 

To create a TypeConverter, simply create a class that inherits from TypeConverter. Then you use the TypeConverterAttribute to tag your class, so that anytime someone tries a convert operation on your class, your TypeConverter is invoked.

Once you inherit from TypeConverter, you should override some of its methods to do what you want. You'd probably want to look at ConvertFrom(), ConvertTo(), and ConvertToString() to start with - that's where you would implement the logic to pull out your localized version of your strings.

To use your TypeConverter, you would code something like this:

var foo = TypeDescriptor.GetConverter(typeof(T));
var mystring = foo.ConvertToString(myObject));

MSDN of course has the documentation and some examples of TypeConverter implementation.

womp
But how do you do the conversion?
Svish
Updated my answer.
womp
+1  A: 

I believe this was already answered: http://stackoverflow.com/questions/796607/how-do-i-override-tostring-in-c-enums/796754#796754

Also, you could combine this with an extension method for enums with a name like ToDisplayString.

Steven Sudit