I'm trying to learn more about how lambdas work in C# and I'm a bit confused by the following example.
I have a weighted average function:
public static double? WeightedAverage<T>(this IEnumerable<T> records, Func<T, double?> value, Func<T, double?> weight)
{
// snip actual calculation code
if (denominator != 0)
return numerator / denominator;
return null;
}
In one place, I use a helper function that has a return type of double
:
static double GetQuantity(Record record)
{
return record.Quantity * record.Factor;
}
And pass that as the weight
parameter into the weighted average function like this:
return _records.WeightedAverage(r => r.Price, r => ReportHelpers.GetQuantity(r));
The above seems to work fine.
The part that is confusing to me: In a few places ReSharper has recommended that I convert some of my lambdas into method groups. Playing around to try and see how this works, I changed the call to:
return _records.WeightedAverage(r => r.Price, ReportHelpers.GetQuantity);
This results in an error, Expected a method with 'double?' GetQuantity(Record) signature
Can someone tell me exactly what is happening behind the scenes here? Why does the lambda expression not produce a similar error since the return of the GetQuantity
function is double
and not double?
? What is the difference with how the method group vs lambda expressions are being evaluated?
Thanks!