views:

30

answers:

2

In the MSDN I've read this about EnumConverter:

You should never create an instance of an EnumConverter. Instead, call the GetConverter method of the TypeDescriptor class. For more information, see the examples in the TypeConverter base class.

Does anybody know why and is it true for my own implemented converters?

For example, I have class GradientColor and converter GradientColorConverter. Should I write

new GradientColorConverter().ConvertFrom(colorString) 

or

TypeDescriptor.GetConverter(typeof(GradientColor)).ConvertFrom(colorString);

Actually It works in both ways, but which is better?

+3  A: 

I think the latter TypeDescriptor.GetConverter(typeof(GradientColor)) because it allows other converters to add or extend the type converter system when the code is run in a different context (like custom control run in another application with its own custom typeconverters).

crtracy
As I know, the converter type specified in the class attribute. How it can be different in other application?
Andrey M.
TypeDescriptor reads from the type system (attributes, or default type conversion) but then extends it to allow customization at runtime. I've never done it, but it's there in the docs. Take a look at TypeDescriptionProvider. This will make reusing your classes in a later version of your app easier.
crtracy
A: 

The latter. If you change the type converter class you code will still work. Decoupling is good.

Marco
You are right, but in this case the reflection will be used to get converter type from the attribute. not sure that it is good, if I can create converter instance as a static type.
Andrey M.