views:

45

answers:

3

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?

A: 

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.

James Curran
No. It's about the method definition, no issue with calling it.
Dario
what do you mean "Calculate"? (its calculator...)can you please write the whole method as needed to be written?
Guy Z
+1  A: 

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.

Dario
+1  A: 

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.

Reed Copsey