c# - Passing method with list of base type in return type as a parameter causes wrong method signature error -
i'm trying create generic method filter results several method returning lists of types deriving same base type. prepared simplified version of problem:
using system; using system.collections.generic; using system.linq; public class animal { public string name { get; set; } } public class cat : animal { } public class dog : animal { } public class program { public static void main() { console.writeline(getfilteredanimals("pe", getcats)); } private static list<cat> getcats() { return new list<cat>() { new cat { name = "sphinx" }, new cat { name = "persian" } }; } private static list<dog> getdogs() { return new list<dog>() { new dog { name = "bulldog"}, new dog { name = "dalmatian" } }; } private static list<animal> getfilteredanimals(string f, func<list<animal>> method) { var animals = method(); return animals.where(a => a.name.startswith(f)).tolist<animal>(); } }
the method
getfilteredanimals("pe", getcats)
does not work because getcats
not return list of animal
. possible such generic method lists? far know, if used single objects instead of lists work.
the working code here on .net fiddle
assuming you're using c# 4+ , .net 4+, can work using generic covariance:
private static list<animal> getfilteredanimals(string f, func<ienumerable<animal>> method)
a list<cat>
can't treated list<animal>
- can treated ienumerable<animal>
because ienumerable<t>
covariant in t
.
likewise func<t>
covariant in t
, func<list<cat>>
can treated func<ienumerable<animal>>
... compiles.
Comments
Post a Comment