Question

My code is simply:

  public override C Calculator<C>(Team[] teams, Func<Team, C> calculatorFunc)
    {
        return teams.Average(calculatorFunc);
    }     

I get this error:

Error 2 The type arguments for method 'System.Linq.Enumerable.Average(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

How can I fix this?

Was it helpful?

Solution

You can't - at least in the current form. There is no Average overload available that works on completely generic values (i.e. for all types C as you specified).

Average needs lists of numbers (int, double, float ...) or a conversion function that produces numbers. In the current form, you could call Calculator<string> and it would make absolutely no sense to compute the average of strings.

You'll just have to restrict the method to a specific numeric type (or provide overloads), but generics simply won't work.

OTHER TIPS

The Enumerable.Average method does not have an overload which works on a generic type. You're trying to call Average<TSource>(IEnumerable<TSource>, Func<TSource, C>), which does not exist.

In order to use average, you'll need to specify one of the types (for C) that actually exists, such as double, decimal, etc.

Instead of writing:

Calculate(team, calcFunc);

You will have to write:

Calculate<MyClass>(team, calcFunc);

However, you really should know what calculatorFunc is returning --- I'm going to assume that all of the ones you use return the same value type (whether it be decimal or int of float). In which case, you could define it as:

public override int Calculator(Team[] teams, Func<Team, int> calculatorFunc)
{
    return teams.Average(calculatorFunc);
}

Then you have no generics in the declaration at all to worry about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top