Ternary Operator instead of if – else statement in X++
I mainly emphasize on writing the required code. So that I will cut/remove the code whichever is unnecessary. So, when I came across if – else condition, thought of having a single line of code. Then I found this Ternary operator in X .
Ternary operation statement is used for executing conditional code. It can be directly assigned to a variable. It is also possible to do same thing using if – else. But for if - else, it will look like a code flow which increases the code size which is not necessary.
For example, an if – else statement looks like,
int i = 10;
str output;
if (i > 2)
{
output = “true”;
}
else
{
output = “false”;
}
info(strfmt(“%1”,output)); //returns true
Here we have a variable of value 10 and if it is greater than 2 then output will be true which will appear as Infolog.
The same code can be written in little less steps and can directly assign to a variable using Ternary Operation.
int i = 10; str output = i > 2 ? “true” : “false”; info(strfmt(“%1”, output)); //returns true
Here I am directly assigning the value i.e., true or false to the output based on i value.
Like in the ternary operation, after equal to, the first expression is to evaluate the condition. Based on the condition, if it is true then the 2nd expression or value will be assigned to the variable or the 3rd expression or value will be assigned. So, we will get true as a Infolog since i is greater than 2.
Nested Ternary Operator
We sometimes need to write nested Ternary operation.
The below example is taken from standard Microsoft Documentation.
print( (custTable.AccountNum > "1000")
? ( (custTable.AccountNum < "2000")
? "In interval" : "Above 2000"
)
: "low"
);
The code processing logic will be if the customer account number is greater than 1000, then it goes into loop and checks if it is less than 2000. If it is less than 2000, then it prints “In interval” or if it is greater, then it prints “Above 2000”. If the customer number is less than 1000 then it prints low.
Now you must have understood the code flow.
By this, the code actually looks neat and clean with less steps.
So, with simple steps we can complete an if – else using ternary operation. So, it would be better to give the ternary the first preference and then if-else if we have a similar requirement.
The syntax is,
expression1 ? expression2 : expression3
and the explanation is,
expression1 must be a Boolean expression. If expression1 is true, the whole ternary statement resolves to expression2. Otherwise, it resolves to expression3.
expression2 and expression3 must be of the same type as each other.

Like
Report
*This post is locked for comments