Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assign a Func<> using the conditional ternary operator? [duplicate]

Tags:

c#

lambda

func

Update

In C#10, this syntax is now valid and the compiler will infer a 'natural type' for a lambda Example here

C# 9 and Earlier

I am aware that Func<>s cannot be implicitly typed directly via the var keyword, although I was rather hoping that I could do the following assignment of a predicate:

Func<Something, bool> filter = (someBooleanExpressionHere)
   ? x => x.SomeProp < 5
   : x => x.SomeProp >= 5;

However, I get the error cannot resolve the symbol, 'SomeProp'

At the moment, I have resorted to the more cumbersome if branch assignment, which doesn't seem as elegant.

Func<Something, bool> filter;
if (someBooleanExpressionHere)
{
    filter = x => x.SomeProp < 5;
}
else
{
    filter = x => x.SomeProp >= 5;
}

Have I missed something, or will I need to stick with the if-branch assignment?

like image 392
StuartLC Avatar asked Sep 04 '14 14:09

StuartLC


People also ask

How do you use a ternary conditional operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Can we assign value in ternary operator?

The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands. result = 'somethingelse'; The ternary operator shortens this if/else statement into a single statement: result = (condition) ?

Can you call a function in a ternary operator?

Nope, you can only assign values when doing ternary operations, not execute functions.


1 Answers

var filter = (someBooleanExpressionHere)
   ? new Func<Something, bool>(x => x.SomeProp < 5)
   : x => x.SomeProp >= 5;
like image 83
Lee Avatar answered Sep 26 '22 15:09

Lee