Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeConverter cannot convert from some base types to same base types

Why those return true:

  TypeDescriptor.GetConverter(typeof(double)).CanConvertTo(typeof(double));
  TypeDescriptor.GetConverter(typeof(int)).CanConvertTo(typeof(int));

when those return false?

  TypeDescriptor.GetConverter(typeof(decimal)).CanConvertTo(typeof(decimal));
  TypeDescriptor.GetConverter(typeof(bool)).CanConvertTo(typeof(bool));

Event considering that all the converters returned by GetConverter are supposed to only convert the types to and from a string :

  • DoubleConverter
  • Int32Converter
  • DecimalConverter
  • BooleanConverter

I'm using .NET Framework 4.5.2.

like image 616
Matthieu Avatar asked Jun 16 '15 18:06

Matthieu


1 Answers

DecimalConverter (as well as DoubleConverter and Int32Converter) overrides CanConvertTo to indicate it can convert to strings (because that's what base.CanConvertTo does) and all CLR primitive types. From the Reference Source:

public override bool CanConvertTo(ITypeDescriptorContext context, Type t) 
{
    if (base.CanConvertTo(context, t) || t.IsPrimitive) {
        return true;
    }
    return false;
}

decimal is NOT a primitive type from the CLR's perspective, so the converter returns false when passed typeof(decimal).

BooleanConverter does not override CanConvertTo, so it falls to the base implementation which only allows a conversion to string:

public virtual bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) 
{
    return (destinationType == typeof(string));
}

If you're asking why it's designed that way, then only the Framework designers can say, but I suspect it's because it's a trivial check to see if you're trying to convert from one type to the same type.

Considering that their purpose is to convert non-string types to/from strings for displaying in property grids, XAML, etc., it's not surprising that it doesn't fully support non-string conversions.

like image 190
D Stanley Avatar answered Oct 08 '22 14:10

D Stanley