0

Q: Why can the generic arguments to Inferred not be inferred?

When looking at the example below the type T can be inferred as Instance and we can see that we need that method with no arguments which is also supplied. That method returns an TOut which must be an int since we cannot have overloads on return types.

public class Instance
{
    public int Convert()
    {
        return 42;
    }
}

public static class Example
{
    public static void Inferred<T, TOut>(T source, Expression<Func<T, Func<TOut>>> expression)
    {
    }

    public static void Usage()
    {
        var instance = new Instance();
        Inferred(instance, x => x.Convert);
    }
}
Christian
  • 908
  • 1
  • 13
  • 22
  • 1
    I guess because enabling the compiler to infer this would be too much work for too little benefit. Note that in case a reference type is returned inference would not really be possible -- if `Convert` returns `string`, is `TOut` `string` or `object`? – Jon Feb 13 '14 at 12:26
  • See this answer. The seminal text on the subject! Http://stackoverflow.com/questions/3203643/generic-methods-in-net-cannot-have-their-return-types-inferred-why – Baldrick Feb 13 '14 at 12:29
  • Found the correct answer here: http://stackoverflow.com/questions/6229131/why-cant-c-sharp-infer-type-from-this-seemingly-simple-obvious-case/6231921#6231921 – Christian Feb 13 '14 at 12:48

0 Answers0