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 :
I'm using .NET Framework 4.5.2.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With