Branching#
?:
if-else
switch
Ternary conditional operator ?:
#
This is short-hand if-else
:
condition ? consequent : alternative
or in other words:
is this condition true ? yes : no
Example#
Example based on the test code of the previous Lunar Lander Control code. The code tests whether the behavior of the lunar lander control is correct dependent on the altitude and thruster values.
// Assume values
var altitude = 20;
var thruster = true;
var behaviorCorrect = (altitude > 100 && !thruster) ||
(altitude is <= 100 and > 0 && thruster) ||
(altitude <= 0 && !thruster);
Console.WriteLine(behaviorCorrect ? "✅" : "❌");
// ?: operator saves an if-else statement
Activity 15
Copy the code above and convert the ternary conditional operator to a if-else
statement.
Steps:
3 min individually
1 min compare with your partner