Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single call ternary operator

Tags:

.NET now supports the null coalescing operator

var item = aVal ?? aDefaultVal; 

I might be overlooking something obvious, but is there something similar for the ternary operator, such that instead of doing

var item = aclass.amethod() > 5 ? aclass.amethod() : 5; 

it wouldn't be needed to call amethod() twice?

like image 626
Brady Moritz Avatar asked Feb 04 '11 20:02

Brady Moritz


People also ask

Can I call function in ternary operator?

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

What is ternary operator with example?

A ternary operator lets you assign one value to the variable if the condition is true, and another value if the condition is false. The if else block example from above could now be written as shown in the example below. var num = 4, msg = ""; msg = (num === 4) ?

Which is called ternary operator 1 point?

In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c .

How do you use else IFN ternary operator?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement. A ternary operator is written with the syntax of a question mark ( ? ) followed by a colon ( : ), as demonstrated below. In the above statement, the condition is written first, followed by a ? .


2 Answers

var item = Math.Max(5, aclass.amethod());
like image 169
Uwe Keim Avatar answered Sep 18 '22 22:09

Uwe Keim


How about:

var result = aclass.amethod();
var item = result > 5 ? result : 5;

You only need to call aclass.amethod() once, then.

like image 21
CanSpice Avatar answered Sep 21 '22 22:09

CanSpice