How can I assign a Func conditionally between lambdas using the conditional ternary operator?

You can convert a lambda expression to a particular target delegate type, but in order to determine the type of the conditional expression, the compiler needs to know the type of each of the second and third operands. While they’re both just “lambda expression” there’s no conversion from one to the other, so the compiler can’t do anything useful.

I wouldn’t suggest using an assignment, however – a cast is more obvious:

Func<Order, bool> predicate = id == null 
    ? (Func<Order, bool>) (p => p.EmployeeID == null)
    : p => p.EmployeeID == id;

Note that you only need to provide it for one operand, so the compiler can perform the conversion from the other lambda expression.

Leave a Comment