Let’s say you want to store one of two values in a variable but deciding on what value should be stored in the variable is dependent on a condition! For example, there’s an employee and we want to set its salary. If the employee is a manager then the value for its salary is 10000 but if it’s a developer, then its salary is 8000.
This is where we can use the ternary operator.
Basically this operator takes one condition and two values. If the condition was true, it will return the first value but if the result of the condition was false, it will return the second value.
This is the structure of the ternary operator:
condition ? expression_True : expression_False;
condition: the condition is the one that we declare to either return true or false result.
expression_true: This is the first value we set for the ternary operator and it will be returned if the result of the condition is true.
expression_false: This is the second value of the ternary operator and of course it will be returned only if the result of the condition becomes false.
?: between the condition and the first value we use question mark ? to separate them from each other.
:: also between the first and second value, we use colon : to separate these two values from each other as well.
Example:
using System;
namespace quickExample
{
public class Program
{
public static void Main(string[] args)
{
String emp = "Manager";
int salary = emp == "Manager" ? 10000 : 8000;
Console.WriteLine("The salary is: " + salary);
}
}
}
Output: The salary is 10000
In this example, the value of the salary variable is dependent on the value of the emp variable.
If the value of the emp is Manager then the value 10000 will be stored in the salary variable. But if the value of the emp wasn’t Manager then the value 8000 is the one to be stored in the salary variable.