C# has a shortened version of an if else command. The use of it is very easy, if you understand it once
1 2 3 | condition ? first_expression : second_expression; |
Notice:
The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
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"; |