Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this generic cast fail?

I have the following inheritance:

internal abstract class TeraRow{}

internal class xRow : TeraRow {} // xRow is a child of TeraRow

public IEnumerable<TeraRow> Compare(MappedTables which, DateTime selectionStart
        , DateTime selectionEnd, string pwd)
{
    IEnumerable<xRow> result=CompareX();
    return  (IEnumerable<TeraRow>)result; //Invalid Cast Exception? 

}

Unable to cast object of type 'System.Collections.Generic.List1[xRow]' to type 'System.Collections.Generic.IEnumerable1[TeraRow]

Also why do I need to cast it at all?

like image 879
Maslow Avatar asked Nov 30 '22 20:11

Maslow


1 Answers

You need to cast it because IEnumerable<T> is not covariant on T. You can do this:

return result.Cast<TeraRow>();
like image 76
mqp Avatar answered Dec 05 '22 01:12

mqp