Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the compiler resolve these generic types

Tags:

c#

generics

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);
like image 861
Cornelius Avatar asked Feb 22 '13 07:02

Cornelius


1 Answers

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.

like image 92
2 revs Avatar answered Oct 04 '22 16:10

2 revs