Why is Func<T> ambiguous with Func<IEnumerable<T>>?

Posted by Matt Hamilton on Stack Overflow See other posts from Stack Overflow or by Matt Hamilton
Published on 2011-01-01T02:34:07Z Indexed on 2011/01/01 2:53 UTC
Read the original article Hit count: 231

Filed under:
|

This one's got me flummoxed, so I thought I'd ask here in the hope that a C# guru can explain it to me.

Why does this code generate an error?

class Program
{
    static void Main(string[] args)
    {
        Foo(X); // the error is on this line
    }

    static String X() { return "Test"; }

    static void Foo(Func<IEnumerable<String>> x) { }
    static void Foo(Func<String> x) { }
}

The error in question:

Error
    1
    The call is ambiguous between the following methods or properties:
'ConsoleApplication1.Program.Foo(System.Func<System.Collections.Generic.IEnumerable<string>>)' and 'ConsoleApplication1.Program.Foo(System.Func<string>)'
    C:\Users\mabster\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs
    12
    13
    ConsoleApplication1

It doesn't matter what type I use - if you replace the "String" declarations with "int" in that code you'll get the same sort of error. It's like the compiler can't tell the difference between Func<T> and Func<IEnumerable<T>>.

Can someone shed some light on this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics