c# - How can I assign a Func<> conditionally between lambdas using the conditional ternary operator? -


generally, when using conditional operator, here's syntax:

int x = 6; int y = x == 6 ? 5 : 9; 

nothing fancy, pretty straight forward.

now, let's try use when assigning lambda func type. let me explain:

func<order, bool> predicate = id == null     ? p => p.employeeid == null     : p => p.employeeid == id; 

that's same syntax, , should work? right? reason doesn't. compiler gives nice cryptic message:

error 1 type of conditional expression cannot determined because there no implicit conversion between 'lambda expression' , 'lambda expression'

i went ahead , changed syntax , way did work:

func<order, bool> predicate = id == null     ? predicate = p => p.employeeid == null     : predicate = p => p.employeeid == id; 

i'm curious why doesn't work first way?

(side note: ended not needing code, found out when comparing int value against null, use object.equals)

you can convert lambda expression particular target delegate type, in order determine type of conditional expression, compiler needs know type of each of second , third operands. while they're both "lambda expression" there's no conversion 1 other, compiler can't useful.

i wouldn't suggest using assignment, - cast more obvious:

func<order, bool> predicate = id == null      ? (func<order, bool>) (p => p.employeeid == null)     : p => p.employeeid == id; 

note need provide 1 operand, compiler can perform conversion other lambda expression.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

visual studio - Deleting lines of code in a text editor -

What's the encoding type of Android 2.2 push message? -