What is Ternary Operator in C# - Simple Explanation and Example
ternary operator in C# is a shortcut for an if-else statement that returns one of two values based on a condition. It uses the syntax condition ? valueIfTrue : valueIfFalse to choose between two options in a single line.How It Works
The ternary operator in C# works like a quick decision maker. Imagine you are choosing between two snacks based on whether you are hungry or not. Instead of writing a long explanation, you just say: "If I'm hungry, I eat an apple; otherwise, I eat a cookie." The ternary operator does the same for your code.
It checks a condition first. If the condition is true, it picks the first value after the question mark ?. If the condition is false, it picks the second value after the colon :. This way, you can write simple choices in one line instead of multiple lines with if and else.
Example
This example shows how to use the ternary operator to decide if a number is even or odd and print the result.
using System; class Program { static void Main() { int number = 7; string result = (number % 2 == 0) ? "Even" : "Odd"; Console.WriteLine($"The number {number} is {result}."); } }
When to Use
Use the ternary operator when you need to choose between two simple values based on a condition. It makes your code shorter and easier to read for quick decisions.
For example, you can use it to set a message based on user input, assign a value depending on a setting, or return a result without writing a full if-else block. However, avoid using it for complex logic because it can become hard to understand.
Key Points
- The ternary operator is a compact form of
if-elsethat returns one of two values. - It uses the syntax
condition ? valueIfTrue : valueIfFalse. - It is best for simple decisions to keep code clean and readable.
- Do not use it for complex or nested conditions to avoid confusion.