Short hand if-else

In C#, you can use the ternary operator (known as shorthand if…else) to replace simple if…else statements with more concise syntax. Let’s explore how it works:
variable = (condition) ? expressionTrue : expressionFalse;
  • If the condition evaluates to true, expressionTrue is assigned to the variable.
  • Otherwise, expressionFalse is assigned.

Example

Normal, if…else statement:
int time = 21;
if (time < 19)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
Using the ternary operator:
int time = 21;
string result = (time < 19) ? "Good day." : "Good evening.";
Console.WriteLine(result);

Advantages

Conditional Assignments: Set a variable based on a condition.
Inline Decisions: Use it directly in expressions or method calls.

Post a comment

Leave a Comment

Scroll to Top