complete question before code:
why ienumerable<t>
where t : itest
not accepted receiver of extension method expects this ienumerable<itest>
?
and code:
i have 3 types:
public interface itest { } public class element : itest { } public class elementinfo : itest { }
and 2 extension methods:
public static class extensions { public static ienumerable<elementinfo> method<t>( ienumerable<t> collection) t : itest { → return collection.toinfoobjects(); } public static ienumerable<elementinfo> toinfoobjects( ienumerable<itest> collection) { return collection.select(item => new elementinfo()); } }
the compiler error (on marked line):
cs1929
:'ienumerable<t>'
not contain definition'toinfoobjects'
, best extension method overload'extensions.toinfoobjects(ienumerable<itest>)'
requires receiver of type'ienumerable<itest>'
why so? receiver of toinfoobjects
extension method ienumerable<t>
, generic type constraint, t
must implement itest
.
why receiver not accepted? guess covariance of ienumerable<t>
not sure.
if change toinfoobjects
receive ienumerable<t> t : itest
, ok.
consider this:
public struct valueelement : itest { }
and this:
ienumerable<valueelement> collection = ... collection.method(); //ok, valueelement implement itest, required. collection.toinfoobjects() //error, ienumerable<valueelement> not ienumerable<itest> //variance not work value types.
so not every type allowed method
allowed toinfoobjects
. if add class
constraint t
in method
, code compile.
Comments
Post a Comment