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 resolve the generics to select and this fails:
Foo(stringList);
Foo(objectList);
Foo(enumerableList);
And you have to explicitly specify the generics to use as such:
Foo<IList<string>, string>(stringList);
Foo<IList<object>, object>(objectList);
Foo<List<object>, object>(objectList);
Foo<IList<IEnumerable>, IEnumerable>(enumerableList);
Generic method type inference deliberately does not make any deductions from the constraints. Rather, deductions are made from the arguments and the formal parameters, and then the deduced type arguments are checked against the constraints.
For a detailed discussion of some of the design issues around constraints and method signatures, including several dozen people telling me that I'm wrong to think that the existing design is sensible, see my article on the subject:
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's answer to a similar question.
I decided to copy it, because this question is more concise and clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With