Use the conditional operator (ternary operator ?:) in C#

[conditional operator]

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.”

lblGreeting.Text = (DateTime.Now.Hour < 12) ?
    "Good morning" : "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.

if (DateTime.Now.Hour < 12)
    lblGreeting.Text = "Good morning";
else
    lblGreeting.Text = "Good afternoon";


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in syntax and tagged , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *