Tomlyn icon indicating copy to clipboard operation
Tomlyn copied to clipboard

InvalidCastException when ConvertToModel converts from a list to a non-list

Open GrantShotwell opened this issue 2 years ago • 1 comments

Exception appears to be thrown in SyntaxToModelTransform.GetOrCreateSubObject(...), line 216.

The reason I am getting this exception is because I am trying to use wrappers for various types, and so implemented a ConvertToModel that creates the wrapper from the deserialized value. The error happens when the wrapped type is a list.

If it helps, the ConvertToModel function looks like this:

interface IWrapper<T> { T Value { get; } }
class StructValue<T> : IWrapper<T> where T : struct { /* ... */ }
class ReferenceValue<T> : IWrapper<T> where T : class { /* ... */ }
class ListValue<T> : IWrapper<IList<T>> { /* ... */ }
// ... and others

object? ConvertToModel(object deserialized, Type targetType) {
    // [return deserialized if deserialized.GetType() is already targetType]
    // [return null if targetType does not implement IWrapper]
    return CreateWrapper(deserialized, targetType);
}

This works for StructValue and ReferenceValue, just not ListValue because of the error.

GrantShotwell avatar Aug 03 '23 19:08 GrantShotwell

Similar issue to #97. Probably has won't fix.

xoofx avatar Mar 11 '25 10:03 xoofx