How to use C# Ternary operator(The ? Operator)
Description
The ?
operator is often used to replace
certain types of if-then-else constructions.
It is called a ternary operator because it requires three operands.
Syntax
The ternary operator has the following form:
question ? expression1 : expression2
It can be rewritten as:
if (question == true){
expression1;// w ww . j a v a 2s. c om
}else {
expression2;
}
Example
The following example uses the conditional operator(ternary operator) to get the bigger value:
using System;//from w w w .ja va 2s.c o m
class Program
{
static void Main(string[] args)
{
int i = 1;
int j = 2;
Console.WriteLine(i > j ? i : j);
}
}
The output:
Example 2
Use ternary operator in Console.WriteLine function
using System;//from ww w. j ava 2 s. c o m
class MainClass
{
static void Main()
{
int x = 10, y = 9;
Console.WriteLine("x is{0} greater than y",
x > y // Condition
? "" // Expression 1
: " not"); // Expression 2
y = 11;
Console.WriteLine("x is{0} greater than y",
x > y // Condition
? "" // Expression 1
: " not"); // Expression 2
}
}
The code above generates the following result.
Example 3
The following code
prevents a division by zero using the ?
operator.
using System; // w w w . j av a 2 s . c om
class Example {
public static void Main() {
int result;
for(int i = -5; i < 6; i++) {
result = i != 0 ? 100 / i : 0;
if(i != 0)
Console.WriteLine("100 / " + i + " is " + result);
}
}
}
The code above generates the following result.