Suppose I have a POCO and a List class for them:
class MyClass
{...}
class MyClasses : List<MyClass>
{...}
And the following method to map an IEnumerable<MyClass>
to a MyClasses
list:
public static TListType ToListOfType<TListType, TItemType>(this IEnumerable<TItemType> list) where TListType : IList<TItemType>, new()
{
var ret = new TListType();
foreach (var item in list)
{
ret.Add(item);
}
return ret;
}
I would expect this code to compile, but it doesn't:
var list = someListOfMyClass.ToListOfType<MyClasses>();
but instead I get
Error CS1061 'IEnumerable' does not contain a definition for 'ToListOfType' and no accessible extension method 'ToListOfType' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)
However, this does work:
var list = someListOfMyClass.ToListOfType<MyClasses, MyClass>();
I don't understand why type inference isn't sufficient for the compiler to know what the item type is, since the this
variable is a list of a known type.