2

I'm going to strike a guess at my own question... does the line commented out below fail to compile because methods and funcs are two different things?

Is there any way to avoid typing <string>? If not, is there a reason why? And if I'm right that it is because methods don't cast to funcs or vice-versa, how could the solution to inferring the type of T from Method Test.A be anything other than string in this example?

Forgive me, but it seems strange that I can clearly pass the method Test.A as an argument satisfying another method's parameter signature Func<T, T> (implying in my mind they are interchangeable)... but I don't get any inference for T at the call site.

public static class Test
{
    public static Func<T, T> TestFunc<T>(Func<T, T> input)
    {
        return input;
    }

    public static string A(string val)
    {
        return val;
    }
}

public class TestStuff
{
    [Fact]
    public static void TestMe()
    {
        var expected = Guid.NewGuid().ToString();
        // this fails to compile with
        // 'type arguments for method ... cannot be inferred from usage'
        // var actual = Test.TestFunc(Test.A);
        // this succeeds
        var actual = Test.TestFunc<string>(Test.A);
        // test passes proving a method satisfies a Func<T, T> parameter
        Assert.Equal(expected, actual(expected));
    }
}
cocogorilla
  • 1,815
  • 14
  • 36
  • Particularly worth reading are Eric Lippert's comments on Jeffrey L Whitledge's answer to that other question, I think. They explain the problem quite well, not only the rules as they are but also why the rules are like that and what scenarios make it difficult or complicated to change those rules. –  Jun 07 '16 at 23:40
  • @hvd Ahh, thank you... I had difficulty searching for the answer... I suspect maybe because all the "type inference" matches were misleading. Would etiquette be to delete my post? – cocogorilla Jun 07 '16 at 23:42
  • It's fine to leave your question up. It's a well-asked question, and with the link to the other question, quite possibly useful for other readers too. There's a reason SO normally doesn't delete questions closed as duplicates, but does delete questions closed for other reasons. :) –  Jun 07 '16 at 23:45
  • Further reading: [Anonymous users are (generally) redirected](http://meta.stackoverflow.com/questions/285853/why-do-links-to-duplicate-question-automatically-redirect-to-the-duplicate) And [people that find the question in the future end up being directed to the canonical post with a quality answer](http://meta.stackoverflow.com/a/255980/5240004) – theB Jun 07 '16 at 23:49

0 Answers0