1

Does anyone know why C# is unable to infer the generic type arguments in this example?

var i = "1 2 3 dogs 4 5".Split(' ').SelectWhere(int.TryParse);

Where:

public delegate bool TryConverter<TIn, TOut>(TIn input, out TOut output);

public static IEnumerable<TOut> SelectWhere<TIn, TOut>(this IEnumerable<TIn> source, TryConverter<TIn, TOut> converter)
{
    foreach (TIn input in source)
    {
        if (converter(input, out TOut output))
            yield return output;
    }
}

I have encountered difficulties with type inference and custom delegate types in the past (but, AFAIK, because of the out parameter I'm unable to use my typical fallback to something like Func<TIn, TOut, bool> in this case).

This is obviously not a show-stopper—I can simply specify the type parameters or even do something like new TryConverter<string, int>(int.TryParse). I'm more curious as to why C# can't/won't infer in situations like these.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
md4
  • 1,609
  • 11
  • 13
  • 1
    Related? [Why is C# unable to infer the generic type argument type from a non-generic static method's signature?](https://stackoverflow.com/q/20649168/1364007) – Wai Ha Lee Oct 08 '19 at 22:07
  • 2
    See first answer in marked duplicate. Type inference won't work from bare method group names. The parameter driving inference needs to be of a specific type, or be an anonymous method. If you were to cast the method group name to a delegate type, inference would work (as far as why the language is like this, I can't say authoritatively, but I expect it's because type inference is already involved in converting a method group to a delegate type, and asking the compiler to recursively infer types was impractical or otherwise undesirable) – Peter Duniho Oct 08 '19 at 22:25

0 Answers0