Fix InvalidCastException in Can/ConvertTo methods from KeyConverter #10289
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Sending this in now when #8215 was finally merged as I've discovered this during development of #9697 but wanted to wait until I can fix the TODOs in the unit tests as well.
Fixes
InvalidCastExceptionthrown fromCanConvertTowhen unboxing cast is performed onvaluethat was notnullbut was of a different type thanKeyor the underlying storage (int), e.g. an object or a different value type.Can* methods should not (and converters do not intentionally) throw in them but this is simple a programmer's error, it is not documented behavior either, hence the fix for this.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.keyconverter.canconvertto?view=windowsdesktop-8.0
Fixes the same issue in
ConvertToby throwing the proper (NotSupported) exception.https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.keyconverter.convertto?view=windowsdesktop-8.0
Customer Impact
Less unexpected exceptions thrown.
Regression
No.
Testing
Local build, unit test.
Risk
There might be a concern that a code was passing
intinstead ofKeywhich is the underlying storage type, so it survives the unboxing hard cast that was being performed but not the typeischeck. We may therefore for back-compat include check for bothKeyandintbut other converters just check for their type, so in my honest opinion it would be best to unify the behaviour and mention in release notes.Microsoft Reviewers: Open in CodeFlow