Conditional operator (?:) is the only ternary operator available in C# which operates on three operands. The symbol “?” placed between the first and the second operand , and ” : ” is inserted between the second and third operand. The first operand (or expression) must be a boolean . The conditional operator together with operands form a conditional expression which takes the following form.
1 2 3 |
condition ? first_expression : second_expression; |
example 1:
if else syntax:
1 2 3 4 5 6 7 8 9 |
string str = null, name="Mike"; bool isFriend = false; if (isFriend) { str = "Hey, " + name; } else { str = "Hello, " + name; } Console.WriteLine(str); Console.ReadLine(); |
?: Operator
1 2 3 4 5 6 7 8 9 10 |
string str = null, name="Mike"; bool isFriend = false; //?: operator str = (isFriend ? "Hey, " : "Hello ") + name; Console.WriteLine(str); Console.ReadLine(); |
Example 2:
if else syx:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void getMood(bool isGood) { if (isGood) Console.WriteLine("It is a nice day"); else Console.WriteLine("It is a bad day"); } static void Main(string[] args) { getMood(true); Console.ReadLine(); } |
?: operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static void getMood(bool isGood) { string str = isGood ? "It is a nice day" : "It is a bad day"; Console.WriteLine(str); } static void Main(string[] args) { getMood(true); Console.ReadLine(); } |
Example 3:
1 2 3 4 5 6 7 8 9 10 11 12 |
public static string result(int something) { return (something >0) ? "positive" : "negative"; } static void Main(string[] args) { Console.WriteLine(result(20)); Console.ReadLine(); } |
Example 4:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int input = Convert.ToInt32(Console.ReadLine()); string classify; // if-else construction. if (input > 0) classify = "positive"; else classify = "negative"; // ?: conditional operator. classify = (input > 0) ? "positive" : "negative"; |