Simplifying Boolean Assignment Without the Ternary Operator
When learning C# for the first time, you often encounter code like this:
bool isEven = (number % 2 == 0) ? true : false;
At first, assigning a boolean value using a ternary operator based on the result of a condition may feel natural and familiar. After all, the ternary operator (condition ? A : B
) is a common syntax used for simple branching.
However, the same logic can be written in a much simpler way:
bool isEven = (number % 2 == 0);
Why can you write it this way?
The condition (number % 2 == 0)
already returns a boolean value. So, there's no need to explicitly branch it — you can directly assign the result to a boolean variable.
In other words, if the condition is true, it becomes true
, and if it's false, it becomes false
. The ternary operator in this case is just an unnecessary decoration.
Example Comparison
// Overly verbose
bool isAdult = (age >= 18) ? true : false;
// Cleaner and more intuitive
bool isAdult = (age >= 18);
When is this useful?
- When you want to store a condition in a boolean variable without using
if
or a ternary operator - When you want to improve code readability
- When the variable name clearly communicates the logic (e.g.,
isActive
,isDead
)
Summary
The result of a condition is inherently either true
or false
. You don’t need to write ? true : false
— assigning the condition directly is cleaner and just as effective.
If you're in the habit of using the ternary operator for boolean conditions, take a moment to revisit your code. Sometimes, shorter really is clearer.