Conditional operator is a bit harder to explain. It takes an expression which produces a Boolean result in order to determine which of two other expressions will be calculated and have its value returned as a result. Its sign is * ?:*. Because it uses three operands, it’s called a ternary operator. The

*sign is placed between the first and the second operands, while the*

**?***is placed between the second and the third.*

**:**The complete syntax of the ?: operator is the following:

1 |
operand1 (condition) ? operand2 : operand3 |

In common English, it’s translated as “if operand1 is True, return the value of operand2; if operand1 is False, return operand3”.

As we will see later, conditional operator is similar to an “if…else…” comparison.

Finally, lets give a concrete example of using the conditional operator:

1 2 3 4 5 |
int x = 3; int y = 9; Console.WriteLine(x > y ? "x is greater than y" : "x is less than y"); Console.Read(); |

The output will be:

Reviewing the aftermath, what we did is, we declared two integers, x and y, with the values of * 3*, respectively

*. Then, we used the conditional operator to check if x is greater than y, and output some text if it’s True, and some other text if it’s False.*

**9**You can also combine this operator with assignment. For instance:

1 2 3 |
int x = 3; int y = 9; int z = x > y ? x : y; |

So, in the above example, first, the compiler checks if x is greater than y. If it is, it returns x, if not, returns y. The returned value is then assigned to the integer z.

*The concepts explained in this lesson are also shown visually as part of the following video:*

**EXERCISES**

**1.** Write an expression that checks for a given integer if its third digit (right to left) is 7.

Solution

Guidelines: Divide the number by 100 and save it in a new variable, which then divide by 10 and take the remainder. The remainder of the division by 10 is the third digit of the original number. Check if it is equal to 7.

1 2 3 4 5 6 |
static void Main(string[] args) { int number = 45764; bool isSeven = (number / 100) % 10 == 7 ? true : false; Console.WriteLine("Third digit of {0} is 7", number, isSeven); } |

**2.** You are given number n and position p. Write a sequence of operations that prints the value of **the bit on the position** p in the number (0 or 1). Example: n=35, p=5 -> 1. Another example: n=35, p=6 -> 0.

Solution

Guidelines: Use

**bitwise operations**and display using

**conditional operator**.

1 2 3 4 5 |
static void Main(string[] args) { int n = 35, p = 6, i = 1, mask = i << p; Console.WriteLine((n & mask) != 0 ? "Third bit is 1" : "Third bit is 0"); } |

Tags: conditional operator, conditional processing, operators