Language: EN

csharp-condicional-ternario

What is and how to use the ternary operator

The ternary operator (also known as the conditional operator) is a tool in C# that allows us to perform conditional evaluations concisely in a single line of code.

It is a shorthand way of expressing an if-else statement in situations where we want to assign a value based on a specific condition.

The ternary operator takes three operands. Its basic syntax is as follows:

condition ? true_expression : false_expression
  • Condition: A boolean expression that evaluates to true or false.
  • True Expression: The value assigned if the condition is true.
  • False Expression: The value assigned if the condition is false.

The ternary operator returns the value of the true expression if the condition is true; otherwise, it returns the value of the false expression.

Basic Example

Suppose we want to determine if a number is even or odd and store the result in a variable called “result”. We could write the code as follows:

int number = 10;
string result;

if (number % 2 == 0)
{
    result = "even";
}
else
{
    result = "odd";
}

However, using a ternary conditional, we can simplify this code into a more compact form.

int number = 10;
string result = (number % 2 == 0) ? "even" : "odd";

The ternary conditional allows us to directly assign the result of the evaluation to the variable “result” more concisely.

Nesting

The ternary operator can be nested to perform more complex evaluations. For example,

int number = 10;

string result = (number > 0) ? "positive" : 
                (number < 0) ? "negative" : 
                "zero";

Console.WriteLine($"The number is {result}");

In this example, “positive” is assigned if the number is greater than 0, “negative” if it is less than 0, and “zero” if it is equal to 0.

Very important, use nesting only when the purpose and functionality are clear. If it detracts from readability, consider using another option.

Practical Examples