The Conditional Operator

Although most operators are unary (they require one term, such as myValue++) or binary (they require two terms, such as a+b), there is one ternary operator, which requires three terms, named the conditional operator ( ? : ):

cond-expr ? expression1 :expression2

This operator evaluates a conditional expression (an expression that returns a value of type bool) and then invokes either expression1 if the value returned from the conditional expression is true, or expression2 if the value returned is false. The logic is: “if this is true, do the first; otherwise, do the second.” Example 4-5 illustrates this concept.

Example 4-5. The ternary operator is a simple kind of control flow statement; depending on the value of the expression, it can take one of two stated actions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Example_4_5_ _ _ _Ternary_Operator
{
    class ValuesProgram
    {
        static void Main(  )
        {
            int valueOne = 10;
            int valueTwo = 20;

            int maxValue = valueOne > valueTwo ? valueOne : valueTwo;

            Console.WriteLine("ValueOne: {0}, valueTwo: {1}, maxValue: {2}",
              valueOne, valueTwo, maxValue);

        }
    }
}

The output looks like this:

ValueOne: 10, valueTwo: 20, maxValue: 20

In Example 4-5, the ternary operator is being used to test whether valueOne is greater than valueTwo. If so, the value of valueOne is assigned to the integer variable maxValue; otherwise, the value of valueTwo is assigned to maxValue.

As with the increment operator, although the conditional operator can save you some keystrokes, you can achieve the same effect with an if statement, which we’ll discuss in Chapter 5. If you think there may be some confusion as a result of using the conditional operator, you’re probably better off writing it out.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.