csharp-condicional-ternario

What is and how to use the ternary operator

  • 3 min

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

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

If you want to learn more, check out the Introduction to Programming Course

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

condition ? true_expression : false_expression
Copied!
  • 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";
}
Copied!

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";
Copied!

The ternary conditional allows us to directly assign the result of the evaluation to the “result” variable in a more concise way.

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}");
Copied!

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

Very important: only use nesting when the purpose and functionality remain very clear. If you see that it harms readability, use another option.

Practical Examples