18

In the following code:

public class A
{
    public decimal Decimal { get; set; }
}

public decimal Test()
{
    return new List<A>().Sum(SumDecimal);
}

public decimal SumDecimal(A a)
{
    return a.Decimal;
}

The line return new List<A>().Sum(SumDecimal); has an error stating that the SumDecimal is an ambiguous invocation.

Why isn't the compiler able to infer the type of SumDecimal. The following works, however:

return new List<A>().Sum((Func<A, decimal>) SumDecimal);

And of course, the usual lambda way works too:

return new List<A>().Sum(x => SumDecimal(x));

On more experimentation, if I write an extension method of my own:

public static class MyExtensions
{
    public static T MySum<T, T2>(this IEnumerable<T2> ie, Func<T2, T> d)
    {
        return default(T);
    }
}

and call that, the compiler infers just fine:

return new List<A>().MySum(SumDecimal);

I see that IEnumerable<T>.Sum is overloaded for int, decimal etc:

public static int Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int> selector)
{
  return Enumerable.Sum(Enumerable.Select<TSource, int>(source, selector));
}

and not like how I have defined. But still, is it just that the compiler's type inference is weak and it is not able to figure it out?

manojlds
  • 290,304
  • 63
  • 469
  • 417

0 Answers0