Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lookup and invoke a .Net TypeConverter for a particular type?

I would like to implement a general purpose runtime type conversion function that makes use .Net TypeConverters to do the conversion.

Does anyone know how to how to look up and invoke a TypeConverter for a particular type?

Consider this C# example:

//
// Convert obj to the type specified by 'toType'.
// 
object ConvertTo(object obj, Type toType)
{
    if (TypeIsEqualOrDerivesFrom(obj.GetType(), toType)) <-- I know how to implement this.
    {
        // The type of obj is the same as the type specified by 'toType' or
        // the type of obj derives from the type specified by 'toType'.
        return obj;
    }

    if (TypeConverterExists(obj.GetType(), toType) <-- How do I implement this?
    {
        // There exists a type convertor that is capable of converting from 
        // the type of obj to the type specified by 'toType'.
        return InvokeTypeConverter(obj, toType); <-- How do I implement this?
    }

    throw new TypeConversionFailedException();
}
like image 712
Ashley Davis Avatar asked Jun 05 '09 14:06

Ashley Davis


People also ask

What is TypeConverter C#?

CanConvertTo(Type) Returns whether this converter can convert the object to the specified type. ConvertFrom(ITypeDescriptorContext, CultureInfo, Object) Converts the given object to the type of this converter, using the specified context and culture information. ConvertFrom(Object)

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 in android?

Use type converters You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.


2 Answers

I don't know how robust it is, but I sometimes use this code for generic type conversion :

public T ConvertTo<T>(object value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

I don't know if the ChangeType method use TypeConverters...

like image 172
Thomas Levesque Avatar answered Nov 15 '22 19:11

Thomas Levesque


    TypeConverter converter = TypeDescriptor.GetConverter(sourceType);
    if(converter.CanConvertTo(destinationType)) {
        return converter.ConvertTo(obj, destinationType);   
    }
    converter = TypeDescriptor.GetConverter(destinationType);
    if(converter.CanConvertFrom(sourceType)) {
        return converter.ConvertFrom(obj);
    }

You could also look at Convert.ChangeType(obj, destinationType)

like image 24
Marc Gravell Avatar answered Nov 15 '22 20:11

Marc Gravell