1

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?

Community
  • 1
  • 1
Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
  • 1
    I asked the same thing a few days ago. Please read [Eric Lippert's answer](http://stackoverflow.com/questions/7171067/no-type-inference-with-generic-extension-method/7171527#7171527) to understand why it doesn't work. – Daniel Hilgarth Aug 29 '11 at 10:28
  • Thanks. My question has two parts: why does the compiler do this? Answer: it doesn't consider constraints (Thanks Eric Lippert). The obvious second part of the question is, why does the compiler not consider constraints? In the argument between you and E. Lippert I have to agree with you: I'd like to see an example of what would have been problematic/unintuitive with another design decision, or a technical argument for this decision (simpler/faster compiler for example). Such a question is perhaps not easily answered on a community site though, so I'll close this Q. Thanks- – Anders Forsgren Aug 29 '11 at 11:18
  • Your second question is answered in the link provided by Eric as well as in the comments to that blog post. – Daniel Hilgarth Aug 29 '11 at 11:20
  • Wow that is a lot of comments... any particular comment where someone presents a simple example of problems occuring with constraints in the method resolution? – Anders Forsgren Aug 29 '11 at 11:32
  • I don't know. I stopped reading after the first page. However, Eric's explanations seems to be somewhat of the "official" reasoning behind this... – Daniel Hilgarth Aug 29 '11 at 11:34

0 Answers0