Why the compiler cannot solve these common types

If I have a method as such:

public void Foo<T1, T2>(T1 list) where T1 : IList<T2> where T2 : class { // Do stuff } 

Now if I have:

 IList<string> stringList = new List<string>(); List<object> objectList = new List<object>(); IList<IEnumerable> enumerableList = new List<IEnumerable>(); 

Then the compiler cannot allow the choice of generators, and this fails:

 Foo(stringList); Foo(objectList); Foo(enumerableList); 

And you should explicitly specify the general to use as such:

 Foo<IList<string>, string>(stringList); Foo<IList<object>, object>(objectList); Foo<List<object>, object>(objectList); Foo<IList<IEnumerable>, IEnumerable>(enumerableList); 
+8
generics c #
source share
1 answer

Inference of the type of a general method intentionally does not deduct any restrictions. Rather, conclusions are drawn from arguments and formal parameters, and then arguments of the inferred type are checked for restrictions.

A detailed discussion of some design issues around limitations and method signatures, including several dozen people who tell me that I am wrong, believe that the existing design is reasonable, see my related article:

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

This is an exact copy of Eric Lippert answers a similar question .
I decided to copy it, because this question is more concise and clear.

+5
source share

All Articles