C# > Core C# > Control Flow > if, else if, else Statements
Conditional Operator (Ternary Operator) Example
This snippet demonstrates the use of the conditional (ternary) operator as a concise alternative to a simple `if-else` statement.
Code Example
This code uses the ternary operator `(age >= 18) ? "Eligible to vote" : "Not eligible to vote"` to determine a message based on the value of the `age` variable. If `age` is greater than or equal to 18, the message "Eligible to vote" is assigned to the `message` variable; otherwise, the message "Not eligible to vote" is assigned. The `Console.WriteLine` statement then prints the appropriate message.
using System;
public class TernaryOperatorExample
{
public static void Main(string[] args)
{
int age = 20;
string message = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
Console.WriteLine(message);
}
}
Concepts Behind the Snippet
The ternary operator provides a shorthand way to write a simple `if-else` statement in a single line of code. It has the following syntax: `condition ? expression1 : expression2`. If the `condition` is true, `expression1` is evaluated and its value is returned. If the `condition` is false, `expression2` is evaluated and its value is returned. The result of the expression becomes the value of what is on the left side of the = operator.
Real-Life Use Case
Consider displaying a different welcome message based on the user's login status. You could use the ternary operator like this:
string welcomeMessage = isLoggedIn ? "Welcome back!" : "Please log in.";
Best Practices
Interview Tip
Be prepared to explain the advantages and disadvantages of using the ternary operator compared to a traditional `if-else` statement. Understand when it's appropriate to use one over the other.
When to Use Them
The ternary operator is best suited for simple `if-else` conditions where you want to assign a value to a variable based on a boolean condition. It's a good choice for situations where brevity is important and the logic is straightforward.
Alternatives
Pros
Cons
FAQ
-
Can I use the ternary operator for more complex conditions?
While you technically can, it's generally not recommended. For complex conditions, using a traditional `if-else` statement is usually more readable and maintainable. -
Is the ternary operator more efficient than an `if-else` statement?
The performance difference between the ternary operator and an `if-else` statement is usually negligible. Readability and maintainability should be the primary considerations when choosing between them.