Index
1 - What is the ternary operator
As we saw in the decision making statement post, C# lets us make decisions through conditionals, like if
for example.
C# includes a special type of decision-making tool called the ternary operator
, which is represented by the character ?
and will always return a boolean
, therefore true
or false
.
The syntax of the statement is as follows:
Expresión booleana ? sentencia 1 : sentencia 2;
As you can see, the statement is made up of three parts:
- The boolean expression; this returns either true or false. (before the question mark
?
) - Statement 1; this is the expression that gets returned if the boolean expression is
true
. (before the colon:
) - Statement 2; this is the expression that gets returned if the expression returns
false
;
So we can see the ternary expression as:
resultado = condicion ? true : false;
1.1 - Turning If into a ternary operator
In this example, we’ll see the result of checking if a person is over 18 with a regular if statement.
if (mayoriaEdad <= edadActual)
{
resultado = "El usuario es mayor de edad";
}
else
{
resultado = "El usuario es menor de edad";
}
And then with a ternary operator:
resultado = mayoriaEdad <= edadActual ? "El usuario es mayor de edad" : "El usuario es menor de edad";
As we can see, everything looks much cleaner, but let’s take a closer look at how the transformation worked:
2 - Nested ternary operators
Of course, it is important to note that we can use nested ternary operators, meaning one inside another. These execute from right to left, not left to right.
- Suppose for example the legal age is 18
- The age to consume alcoholic beverages is 21
- And finally, the age to drive is 25
So, we have 3 conditionals and a total of 7 options in the equation.
int mayoria = 18, votar = 21, conducir = 25, edadactual=25;
resultado = conducir <= edadactual ? "puede conducir y votar" : votar <= edadactual ?
"puede votar" : mayoria <= edadactual ?
"es mayor de edad" : "No puede hacer nada";
This can be expressed as a ? b : c ? d : e ? f : g
which is evaluated as a ? b : (c ? d : (e ? f : g))
So, if we make a small change to the previous code and swap the order of legal age and driving
resultado = mayoria <= edadactual ? "es mayor de edad" : votar <= edadactual ?
"puede votar" : conducir <= edadactual ?
"puede conducir" : "No puede hacer nada";
As we can see, we will usually use ternary expressions to replace a simple if else
statement, which will help us keep our code cleaner.
If there is any problem you can add a comment bellow or contact me in the website's contact form