Why is the FormatException returned by TypeConverter for type ushort related to Int16?

I am writing my code in C # and .NET Core 2.0.5. When using TypeConverter for a ushort type and with a conversion error, the FormatException message refers to Int16, not UInt16. Can anyone explain this to me?

Other types that I tested with (decimal, double, float, int, long, short, uint, ulong) return the expected type name in the error message.

To show your point, here is a unittest that will fail. The error message states that "badvalue is not a valid value for Int16."

[Fact] public void FailingToConvertUShort_GivesFormatExceptionMessage_WithCorrectType() { // Arrange var badvalue = "badvalue"; var typeConverter = TypeDescriptor.GetConverter(typeof(ushort)); try { // Act var result = typeConverter.ConvertFrom(context: null, culture: new CultureInfo("en-GB"), value: badvalue); } catch (Exception ex) { // Assert Assert.Equal($"badvalue is not a valid value for {typeof(ushort).Name}.", ex.Message); } } 

This is the test result:

Expected: ··· t is a valid value for UInt16.

Actual: ··· t is a valid value for Int16.

+5
source share
1 answer

This is an error in UInt16Converter (the type that you return using TypeDescriptor.GetConverter(typeof(ushort)) . In particular, this line :

 internal override Type TargetType => typeof(short); 

should explicitly read ushort , not short . This error was introduced as part of the cleanout commit to use expressive members.

The only thing that affected the exception message. It also selects a slightly different code path in TypeConverter.ConvertTo when converting to strings, but this does not affect the formatting of UInt16 values. Note that the tests for this class do not apply to this: they only confirm that ConvertFrom throws an invalid value, but not what type of exception or message content. (The latter is almost certainly by design, since the .NET exception messages are localized.)

+2
source

Source: https://habr.com/ru/post/1275951/


All Articles