BLOG.CSHARPHELPER.COM: Use the conditional (ternary) ?: operator in C#
Use the conditional (ternary) ?: operator in C#
The conditional operator (also called the ternary operator) evaluates a Boolean expression and returns one of two values depending on the result. If the expression is true, the operator returns the first value. If the expression is false, the operator returns the second value.
The following code evaluates the Boolean expression (DateTime.Now.Hour < 12). If this expression is true, the operator returns "Good morning." If the value is false, the operator returns "Good afternoon."
The conditional operator can be confusing so I tend to use it very sparingly, preferring to use if-then-else statements in most cases. For example, the following code is equivalent to the previous version but doesn't use the conditional operator.
Comments