#92 – The Ternary Conditional Operator

The conditional operator (?:) take three operands.  The first is a boolean expression to evaluate. If this expression is true, the value of the conditional operator is equal to the second operand.  If it’s false, the value of the conditional operator is equal to the third operand.

So for the expression

 a ? b : c

the value of this expression is b if a is true, or c if a is false.

Here’s an example of using the conditional operator (assume that isRaining is a boolean):

string describeWeather = isRaining ? "Wet" : "Nice";

A conditional operator can always be rewritten as an if statement.  The previous example is equivalent to:

string describeWeather;
if (isRaining)
    describeWeather = "Wet";
else
    describeWeather = "Nice";

Using the conditional operator can lead to more concise code.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers