Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Func and Conditional Operator

Tags:

c#

Duplicate

I can do this:

Func<CategorySummary, decimal> orderByFunc;
if (orderBy == OrderProductsByProperty.Speed)
     orderByFunc = x => x.Speed;
else
    orderByFunc = x => x.Price;

Why can't I do this:

Func<CategorySummary, decimal> orderByFunc = (orderBy == OrderProductsByProperty.Speed) ? x => x.Speed : x => x.Price;
like image 753
pondermatic Avatar asked May 17 '09 03:05

pondermatic


2 Answers

The 'type inference' on the conditional operator is not quite good enough, I get a message like

Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'

you can always just be explicit on the right-hand-side, a la

var o = true ? new Func<int,int>(x => 0) : new Func<int,int>(x => 1);

In any case it's just a minor annoyance regarding how the types of lambdas, type inference, and the conditional operator interact.

like image 68
Brian Avatar answered Oct 10 '22 23:10

Brian


Just cast the lambda's to Func<CategorySummary, decimal> and it will work

like image 23
bashmohandes Avatar answered Oct 10 '22 22:10

bashmohandes