Cornelius
Cornelius

Reputation: 3616

Why can't the compiler resolve these generic 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 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);

Upvotes: 8

Views: 1519

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

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.

Upvotes: 5

Related Questions