Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you assign a TypeConverter without a TypeConverterAttribute?

Dependency requirements are forcing me to have a class and its TypeConverter in different assemblies.

Is there a way to assign a TypeConverter to a class without using a TypeConverterAttribute, and thus causing circular assembly references.

Thanks.

like image 485
Spike Avatar asked Jun 18 '10 09:06

Spike


People also ask

What is a TypeConverter?

Type converters let you convert one type to another type. Each type that you declare can optionally have a TypeConverter associated with it using the TypeConverterAttribute. If you do not specify one the class will inherit a TypeConverter from its base class.

What is TypeConverter C#?

Provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties.


2 Answers

Hmm, not sure I've seen this before, but you could add the TypeConverterAttribute at runtime using a TypeDescriptor, so given my sample classes:

public class MyType
{
    public string Name;
}

public class MyTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        if (sourceType == typeof(string))
            return true;

        return base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        if (value.GetType() == typeof(string))
            return new MyType() { Name = (string) value };

        return base.ConvertFrom(context, culture, value);
    }
}

I could then have a method:

public void AssignTypeConverter<IType, IConverterType>()
{
  TypeDescriptor.AddAttributes(typeof(IType), new TypeConverterAttribute(typeof(IConverterType)));
}

AssignTypeConverter<MyType, MyTypeConverter>();

Hope that helps.

like image 51
Matthew Abbott Avatar answered Oct 03 '22 20:10

Matthew Abbott


You can still use TypeConverterAttribute and use its constructor which accepts a fully qualified name. See MSDN.

like image 35
Patko Avatar answered Oct 03 '22 20:10

Patko