In this answer, I wrote a LINQ extension that utilizes the following delegate
, so I can pass in a function with an out
variable, such as int.TryParse
:
public delegate bool TryFunc<TSource, TResult>(TSource source, out TResult result);
public static IEnumerable<TResult> SelectTry<TSource, TResult>(
this IEnumerable<TSource> source, TryFunc<TSource, TResult> selector)
{
foreach (TSource item in source)
{
TResult result;
if (selector(item, out result))
{
yield return result;
}
}
}
In order to use this extension, I have to explicitly specify the <string, int>
types like so:
"1,2,3,4,s,6".Split(',').SelectTry<string, int>(int.TryParse); // [1,2,3,4,6]
I want to remove <string, int>
, similar to how we can call .Select(int.Parse)
without specifying <int>
, but when I do, I get the following error:
The type arguments for method 'LINQExtensions.SelectTry(IEnumerable, LINQExtensions.TryFunc)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
My question is, why can't the types be inferred? My understanding is that the compiler should know the signatures of int.TryParse
and subsequently the TryFunc
delegate
at compile time.