C# overloading with generics: bug or feature?
Posted
by TN
on Stack Overflow
See other posts from Stack Overflow
or by TN
Published on 2010-04-06T16:52:59Z
Indexed on
2010/04/06
18:13 UTC
Read the original article
Hit count: 168
Let's have a following simplified example:
void Foo<T>(IEnumerable<T> collection, params T[] items)
{
// ...
}
void Foo<C, T>(C collection, T item)
where C : ICollection<T>
{
// ...
}
void Main()
{
Foo((IEnumerable<int>)new[] { 1 }, 2);
}
Compiler says:
The type 'System.Collections.Generic.IEnumerable' cannot be used as type parameter 'C' in the generic type or method 'UserQuery.Foo(C, T)'. There is no implicit reference conversion from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.ICollection'.
If I change Main
to:
void Main()
{
Foo<int>((IEnumerable<int>)new[] { 1 }, 2);
}
It will work ok. Why compiler does not choose the right overload?
© Stack Overflow or respective owner