CSCI 1301

Ternary Operator

1. Learning Objectives

  • How does ternary operator work?
  • What are some situations where it may be useful?

2. What is Ternary Operator?

The word ternary means composed of three parts. In programming, a ternary operator has 3 operands:

  1. A boolean expression that evaluates to either true or false (1st operand)
  2. A value to be assigned if the expression is evaluated to true (2nd operand)
  3. A value to be assigned if the expression is evaluated to false (3rd operand)

When using a ternary operator, there are two possible outcomes:

  • When the boolean expression is true, the result of the operation is the second operand
  • When the boolean expression is false, the result of the operation is the third operand

Ternary operator is a type of conditional statement. It is especially useful in situations where we want to assign a value to a variable and there exactly two options.

3. Syntax

1booleanExpression ? a : b;
  • ? and : separate the three operands of a ternary operator
  • In C#, the second and third operand can be any type, but their type must be the same.
  • The type of the entire expression will be same as the type of second/third operand.

Examples

Consider the following example:

1string fever = bodyTemperature > 98 ? "yes" : "no";

Assuming a variable bodyTemperature (perhaps obtained from user) has been declared and initialized. In the example above, we compare bodyTemperature and literal value 98.

  • when bodyTemperature is above 98:
    • the boolean expression is true
    • the value of string fever will be yes
  • when bodyTemperature is 98 or less,
    • the boolean expression is false,
    • the value of string fever will be no

Ternary operator works similarly with other data types:

1decimal ticketPrice = age <= 12 ? 3M : 10M;

This statements assigns a value to variable ticketPrice, where children age 12 and below pay $3. For everyone else the ticket price will be $10. Notice the type of the result (ticketPrice) is the same as the type of second and third operand (literals 3M and 10M) they are all decimal type.

4. Using Ternary Operator Instead of if-else Statement

Statements with ternary operator can be used in place of simple if-else statements. You will learn to identify suitable statements over time and with practice, but in general if-else statement that performs a single operation or assignment is a good candidate.

The next example shows a simple program that asks user for age, then displays whether user is old enough to vote based on their age:

1Console.Write("Enter your age: ");
2int age = int.Parse(Console.ReadLine());
3
4if(age >= 18){
5 Console.WriteLine("You can vote!");
6} else {
7 Console.WriteLine("Not old enough to vote yet!");
8}

In the above example we have if-else statement where the statement will display one of two texts as output. The if-else statement can be replaced using ternary operator to create an equivalent program:

1Console.Write("Enter your age: ");
2int age = int.Parse(Console.ReadLine());
3
4// this command replaces the if-else statement
5string message = age >= 18 ? "You can vote!" : "Not old enough to vote yet!";
6
7// this command displays the output
8Console.WriteLine(message);

Since the variable message is only used once, we can simplify even further by removing the variable and placing the ternary operation withing Console.WriteLine:

1Console.Write("Enter your age: ");
2int age = int.Parse(Console.ReadLine());
3Console.WriteLine(age >= 18 ? "You can vote!" : "Not old enough to vote yet!");

We have now gone from original program down to 3 lines of code.

Below is an executable version of the program. Notice it includes both if-else statement and ternary operation. This will allow you to verify that the two statements do indeed produce the same output you will see same output twice.


5. Summary

How does ternary operator work?

Ternary operator uses three operands, where the first operand (boolean expression) is evaluated and if it is true, the resulting value is the second operand. Otherwise the result will be the third operand.

What are some situations where it may be useful?

Ternary operator can help reduce the amount of code needed to perform simple operations in place of if-else statements.