Make use of Ternary (Conditional) Operator – Clean Code Post 2

It is more elegant in code to use the Ternary Operator than an IF statement. The Ternary Operator is also commonly known as the Conditional Operator.

Here is a C# example of a Ternary Operator in use:

int bonus = employee.Age < 50 ? 20 : 40;

You can see that it takes up less lines of code then the IF statement below:

int bonus;

if (employee.Age < 50)
{
  bonus = 20;
}
else
{
  bonus = 50;
}

You can see that it is much cleaner to use the Ternary Operator and results in using one line of code rather than ten.

Leave a comment