Guy Z
Guy Z

Reputation: 693

Using Generic with Func as a parameter

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?

Upvotes: 0

Views: 221

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564413

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.

Upvotes: 1

James Curran
James Curran

Reputation: 103505

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.

Upvotes: 0

Dario
Dario

Reputation: 49218

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.

Upvotes: 1

Related Questions