Possible Duplicate:
No type inference with generic extension method
I have a generic collection-cloning utility that looks like this:
public static TColl CloneCollection<TColl, TItem>(this TColl collection)
where TColl : ICollection<TItem>, new()
where TItem : ICloneable
{
TColl newCollection = new TColl();
collection.ForEach(item => newCollection.Add((TItem) item.Clone()));
return newCollection;
}
For some reason the type inference feels dumber than usual in this scenario. I was expecting it to work like this:
List<Fruit> f = GetSomeFruit();
List<Fruit> f2 = f.CloneCollection();
But I get the "The type arguments for method 'Collections.CloneCollection(TColl)' cannot be inferred from the usage. Try specifying the type arguments explicitly".
Instead, I have to do this:
List<Fruit> f2 = f.CloneCollection<List<Fruit>, Fruit>(fruits);
Can someone explain when the compiler can infer arguments and when it cannot, and specifically why the above example apparently has the compiler fooled?