Monday, May 18, 2015

Ternary Operator (?)

Introduction:

Ternary operator is a conditional statement. It is related to the If condition, but it assigns value to the variable. Based on the scenario, we can use ternary operator instead of If condition.

Syntax:

expression1 ? expression2 : expression3

Expression1 must be a Boolean expression. Expression1 may be a condition for example:

salaryDeduction = calculatedDeduction > 500 ? calculatedDeduction - 500 : 0;

expression2 and expression3 must be a same data type otherwise, it will be consider as error. You may get warning/error message like “Operand types are not compatible with the operator”.

As per the above code if the calculatedDeduction is more than 500 then expression2 result value will be assigned to the variable salaryDeduction else 0 will be assigned to the variable salaryDeduction. It is also possible to use ternary statement nested inside another ternary statement. Last time, I tried this ternary operator in the update_recordset, but not supported.

Replace If condition:

Based on the scenario, we can use ternary operator instead of if condition.

No comments :

Post a Comment