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
6
7
8
9
10
11
12
13
14
15
16
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
int
x =
3;
int
y =
9;
Console.WriteLine(x > y ? "x is greater than y" : "x is less than y");
Console.ReadLine();
}
}
}
|
The output will be:
Reviewing the aftermath, what we did is, we declared two integers, x and y, with the values of 3, respectively 9. 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.
You can also combine this operator with assignment. For instance:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
using
System;
namespace
HelloWorld
{
class
Program
{
static void Main(string[] args)
{
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: