c# - Generic types cannot Cast, although IsAssignableFrom -


i have generic queryprovider can provide (sequences of) data of type upon request.

before providing data check if requested type isassignablefrom type can provide.

the compiler satisfied cast ienumerable<tdata> ienumerable<tresult>, yet complains casting tdata tresult

class myclass<tdata> {     private ienumerable<tdata> getsequence() {return enumerable.empty<tdata>(); }       private tdata getsinglevalue() { return default(tdata); }      public tresult getresult<tresult>()     {         tresult result;         if (typeof(tresult).isassignablefrom(typeof(ienumerable<tdata>)))         {   // can assign ienumerable<tdata> tresult             ienumerable<tdata> data = getsequence();             result = (tresult)data;         }         else if (typeof(tresult).isassignablefrom(typeof(tdata)))         {   // can assing tdata tresult:             tdata data = getsinglevalue();             result = (tresult)data; 

compiler error cs0030 cannot convert type 'tdata' 'tresult'

        }         else             throw new invalidoperationexception("can't provide data");         return result;     } } 

why there no problem casting ienumerable<tdata> ienumerable<tresult>, not possible cast tdata tresult?

addition after comments indeed, isassignable has nothing problem. baffled me ienumerable conversion no problem, while direct conversion is.

of course clause solves problem, changes question: why can ienumerable without clause, , why direct converion need clause:

ienumerable<tdata> items = ...; tdata item = items.firstordefault(); tresult result1 = (ienumerable<tresult>) items;    // compile time ok tresult result2 = (tresult) item;                  // compile time problem    var obj = (object)item; tresult result3 = (tresult) obj;                   // compile time ok; 

could if compiler can't proof explicit cast incorrect, gives me benefit of doubt?

your question , code not lining up. code not attempting cast tdata tresult. attempting cast ienumerable<tdata> `tresult.

if ienumerable<tdata> ienumerable<tresult> valid. ienumerable<tdata> tresult not be.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -