In a C#/WPF application I added a TypeConverter attribute to some of my enums in order to display a localized text instead of the text of the enum:
[TypeConverter(typeof(LocalizedEnumTypeConverter))]
public enum MyEnum
{
EnumVal1 = 0,
EnumVal2 = 1,
EnumVal3 = 2,
}
I have implemented LocalizedEnumTypeConverter to perform this task.
The problem arises when I try to use the same approach with an enum that is defined in another assembly, that has no access to LocalizedEnumTypeConverter, and it is shared with other applications (that is, I cannot add a reference to the assembly where LocalizedEnumTypeConverter is defined).
Is there a way to add the TypeConverter attribute in runtime? This way I can leave the enum in the other assembly without the TypeConverter attribute, and then add it in runtime in my application.
This can be done using TypeDescriptor class https://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor.aspx. Refer the below sample.
Attribute[] newAttributes = new Attribute[1];
newAttributes[0] = new TypeConverterAttribute(typeof(LocalizedEnumTypeConverter));
TypeDescriptor.AddAttributes(typeof(MyEnum), newAttributes);