C# Question Mark Operator
C# has a shortened version of an if else command. The use of it is very easy, if you understand it once
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.
1 2 3 |
condition ? first_expression : second_expression; |
For more examples : C# Question Mark Operator & Examples
Example 1: The greatest number amoung two numbers
1 2 3 4 5 6 7 8 9 10 |
Random rnd = new Random(); var rand1 = rnd.Next(); var rand2 = rnd.Next(); var greater = rand1 > rand2 ? rand1 : rand2; Console.WriteLine(" Number 1:{0} \n Number 2:{1} \n The greatest number amoung two numbers {2}",rand1,rand2,greater); Console.ReadLine(); |
Example 2:(Alternative solution)
1 2 3 4 5 6 7 8 9 |
Random rnd = new Random(); var randomNumber = rnd.Next(); var result = randomNumber % 2 == 0 ? "even" : "odd"; Console.WriteLine("{0} is an {1} number. ", randomNumber, result); Console.ReadLine(); |