dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.17k stars 4.72k forks source link

Strange behavior of System.ComponentModel.Int128Converter #109148

Open mata007 opened 2 hours ago

mata007 commented 2 hours ago

Description

It seems to me that the class System.ComponentModel.Int128Converter is incorrectly implemented. It only implements conversions from strings and leaves everything else to the base class implementation (BaseNumberConverter). BaseNumberConverter works correctly as a base for converters of primitive types, but not for the new types Int128, UInt128, and Half.

For conversion to primitive types, CanConvertTo returns true, but ConvertTo throws an exception, stating that the input object does not implement IConvertible.

This is caused by the code below in the BaseNumberConverter.ConvertTo method.

if (destinationType.IsPrimitive)
    return Convert.ChangeType(value, destinationType, culture);

Int128Converter by pravděpodobně měl mít vlastní implementaci CanConvertTo a ConvertTo.

Reproduction Steps

Example of use

using System.ComponentModel;
using System.Reflection.Metadata;

int result;
object value = (Int128)1234;
var converter = TypeDescriptor.GetConverter(value.GetType());
if (converter.CanConvertTo(typeof(int)))
    result = (int)converter.ConvertTo(value, typeof(int));

The last line of code throws an exception: "System.InvalidCastException: Object must implement IConvertible."

Expected behavior

I would expect Int128Converter to allow conversions to and from primitive numeric types, since Int128 has overloaded operators for casting to all of these types.

Actual behavior

As I mentioned above, Int128Converter.ConvertTo throws an exception "System.InvalidCastException: Object must implement IConvertible" when converting to primitive numeric types.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

dotnet-policy-service[bot] commented 2 hours ago

Tagging subscribers to this area: @dotnet/area-system-componentmodel See info in area-owners.md if you want to be subscribed.