Ternary Operator
Part of the Fundamentals section of Coddy's C# journey — lesson 28 of 69.
The ternary operator is a simple one-line if-else statement. It has the following syntax:
variable = (condition) ? value_if_true : value_if_false;The ternary operator evaluates the condition. If it's true, it assigns value_if_true to the variable; otherwise, it assigns value_if_false.
For example:
int age = 20;
string message = (age >= 18) ? "Adult" : "Minor";In this example, since age is greater than or equal to 18, message will be assigned the value "Adult". If age were less than 18, message would be assigned "Minor".
You can nest ternary operators to handle multiple conditions:
int score = 75;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F";This checks multiple conditions in order. If score >= 90, grade is "A"; else if score >= 80, grade is "B"; else if score >= 70, grade is "C"; otherwise "F".
Note: Nested ternary operators can be hard to read. For complex conditions, use if-else statements instead.
Challenge
BeginnerCreate a program that checks if a number is positive, negative, or zero using the ternary operator. The program should:
- Take an integer input from the user.
- Use the ternary operator to determine if the number is positive, negative, or zero. Save
positive,negativeorzerostring inresult. - Print the result in the format:
"The number is [positive/negative/zero]".
You can use a nested ternary to solve this problem.
Cheat sheet
The ternary operator is a one-line if-else statement with the syntax:
variable = (condition) ? value_if_true : value_if_false;It evaluates the condition and assigns value_if_true if the condition is true, otherwise assigns value_if_false.
Example:
int age = 20;
string message = (age >= 18) ? "Adult" : "Minor";Nested ternary operators to handle multiple conditions:
int score = 75;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : "F";This checks multiple conditions in order. If score >= 90, grade is "A"; else if score >= 80, grade is "B"; else if score >= 70, grade is "C"; otherwise "F".
Note: Nested ternary operators can be hard to read. For complex conditions, use if-else statements instead.
Try it yourself
using System;
public class Program {
public static void Main(string[] args) {
int number = int.Parse(Console.ReadLine());
string result = "";
// Write your code below
Console.WriteLine("The number is " + result);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 36Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else