Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

Shortcutting with the Conditional Operator

C# has one ternary operator: the conditional operator. The conditional operator has the following format:

Condition ? if_true_statement : if_false_statement;

As you can see, there are three parts to this operation, with two symbols used to separate them. The first part of the command is a condition. This is just like the conditions that you created earlier for the if statement. This can be any condition that results in either true or false.

After the condition is a question mark, which separates the condition from the first of two statements. The first of the two statements executes if the condition is true. The second statement is separated from the first with a colon and is executed if the condition is false. Listing 3.6 presents the conditional operator in action.

The conditional operator is used to create concise code. If you have a simple if statement that evaluates to doing a simple true and simple false statement, then the conditional operator can be used. In my opinion, you should avoid the use of the conditional operator. Because it is just a shortcut version of an if statement, just stick with using the if statement. Most people reviewing your code will find the if statement easier to read and understand.

Listing 3.6 cond.cs—The Conditional Operator in Action

 1: // cond.cs - The conditional operator
 2: //----------------------------------------------------
 4: class cond
 5: {                       
 6:   public static void Main()
 7:   {
 8:    int Val1 = 1;
 9:    int Val2 = 0;
10:    int result;
12:    result = (Val1 == Val2) ? 1 : 0;
14:    System.Console.WriteLine("The result is {0}", result);
15:   }
16: }
The result is 0

This listing is very simple. In Line 12, the conditional operator is executed and the result is placed in the variable result. Line 14 then prints this value. In this case, the conditional operator checks to see whether the value in Val1 is equal to the value in Val2. Because 1 is not equal to 0, the false result of the conditional is set. Modify Line 8 so that Val2 is set equal to 1, and then rerun this listing. You will see that because 1 is equal to 1, the result will be 1 instead of 0.


The conditional operator provides a shortcut for implementing an if statement. Although it is more concise, it is not always the easiest to understand. When using the conditional operator, you should verify that you are not making your code harder to understand.

  • + Share This
  • 🔖 Save To Your Account