Shorthand If-Else Condition Using C# Ternary Operator

R M Shahidul Islam Shahed
2 min readAug 5, 2023

The ternary operator in C# is a shorthand way of writing an if-else statement in a single line. It allows you to assign a value to a variable based on a condition.

Shorthand If-Else Condition Using C# Ternary Operator

The syntax of the ternary operator is as follows:

variable = condition ? valueIfTrue : valueIfFalse;

Here’s how it works:

  • If the condition is true, the value of valueIfTrue is assigned to the variable.
  • If the condition is false, the value of valueIfFalse is assigned to the variable.

Here’s an example to illustrate the use of the ternary operator:

int age = 25;
string message = (age >= 18) ? "You are an adult." : "You are a minor.";

Console.WriteLine(message);

Output:

You are an adult.

In this example, the ternary operator checks if the age variable is greater than or equal to 18. If the condition is true, the value "You are an adult." is assigned to the message variable. Otherwise, if the condition is false, the value "You are a minor." is assigned to the message variable.

Here’s an example 2 to illustrate the use of the ternary operator:

var _UserProfile = await _context.UserProfile.Where(x => x.Id==…

--

--