.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?
Nope, you can only assign values when doing ternary operations, not execute functions.
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) ?
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 .
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 ? .
var item = Math.Max(5, aclass.amethod());
How about:
var result = aclass.amethod();
var item = result > 5 ? result : 5;
You only need to call aclass.amethod()
once, then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With