The conditional operator ?:, also known as the ternary conditional operator, evaluates a Boolean expression and returns the result of one of the two expressions, depending on whether the Boolean expression evaluates to true or false
The ternary operator can be used instead of an if else
Syntax
Condition ? statement1 : statement2;
The ternary operator starts with a boolean condition. If this condition evaluates to true then it will execute statement1 after the ?, otherwise statement2 after the : will be executed.
Example 1
In this example we show you an if else statement and how it would be written using the ternary operator
using System; public class Program { public static void Main() { int x = 10, y = 20; string result; // if...else example if (x > y) { result = "x greater than y"; } else { result = "x less than y"; } Console.WriteLine(result); //Ternary Operator (?:) statement result = (x > y) ? "x greater than y" : "x less than y"; Console.WriteLine(result); } }
When you run this you will see something like this
x less than y x less than y
Reverse the numbers and run the example again like this
using System; public class Program { public static void Main() { int x = 20, y = 10; string result; // if...else example if (x > y) { result = "x greater than y"; } else { result = "x less than y"; } Console.WriteLine(result); //Ternary Operator (?:) statement result = (x > y) ? "x greater than y" : "x less than y"; Console.WriteLine(result); } }
You will see something like this
x greater than y x greater than y
Nested Ternary Operator
You can also create a nested ternary operator by including multiple conditional expressions as a second or third part of expressions in the ternary operator.
This means you can replace an if else if else statement
Here is an example
Example
using System; public class Program { public static void Main() { int x = 20, y = 20; // If...else If Statement example string result; if (x > y) { result = "x is greater than y"; } else if (x < y) { result = "x is less than y"; } else { result = "x is equal to y"; } Console.WriteLine(result); //Nested Ternary Operator (?:) result = (x > y) ? "x is greater than y" : (x < y) ? "x is less than y" : "x is equal to y"; Console.WriteLine(result); } }
Run this and you will see something like this
x is equal to y x is equal to y
You can change the x and y values and run again to see the different results