Ternary Operator in C#

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:

  1. The boolean expression; this returns either true or false. (before the question mark ?)
  2. Statement 1; this is the expression that gets returned if the boolean expression is true. (before the colon :)
  3. 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:

if to ternary operator

 

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.

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café