C# – Unable to cast object of type System.Collections.Generic.List[System.Object] to type System.Collections.Generic.IList[ShortCodeList]

cgenerics

The BindingProperties returns the Type T. The result the linq query brings at runtime is System.Collections.Generic.IList[ShortCodeList] but when I try to type cast it with IList T>, it returns:

Unable to cast object of type
'System.Collections.Generic.List`1[System.Object]' to type
'System.Collections.Generic.IList`1[ModelAccessLayer.Model.ShortCodeList]'

    private IList<T> GetResultSetConvertedToList<T>(IList<T> dataSet, IEnumerable<dynamic> resultSet) where T : class, new()
    {
        IList<T> customResult = (IList<T>)(resultSet.Select(x => BindingProperties(new T(), x)).ToList());
        return customResult;
    }

Could anyone help me out with this issue?

Best Answer

The type dynamic in the select expression causes the whole expression to be treated as a dynamic expression, returning a IEnumerable<dynamic>

If you explicitly tell C# to use .Select<dynamic,T>, you can force the return type to be T and your code will work as expected.

    private IList<T> GetResultSetConvertedToList<T>(IList<T> dataSet, IEnumerable<dynamic> resultSet)
        where T : class, new()
    {
        IList<T> customResult = (IList<T>)(resultSet.Select<dynamic, T>(x => BindingProperties(new T(), x)).ToList());
        return customResult;
    }