[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

[Use the conditional operator (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."

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 the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.