Code

Conditional Operator ( ?: )

Ternary Operator ( ? : )

C# provides a conditional operator, which is sometimes called ternary or question operator. The conditional operator ?: uses the Boolean value of an expression to determine which of two other expressions must be calculated and returned as a result.

Syntax

c# ternary operator

Example 1
bool loggedIn = true;
string status = loggedIn ? "Online" : "Offline";
Console.WriteLine($"User is {status}"); // Print

The above code is equivalent to the following:

bool loggedIn = true;
string status = String.Empty;
if (loggedIn)
    status = "Online";
else
    status = "Offline";

Console.WriteLine($"User is {status}"); // Print
OUTPUT

User is Online

Run Demo

Example 2
int number = 3;
string value = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine($"{number} is {value}");

The above code is equivalent to the following:

int number = 3;
string value = String.Empty;
if (number % 2 == 0)
    value = "Even";
else
    value = "Odd";

Console.WriteLine($"{number} is {value}");
OUTPUT

3 is Odd

Run Demo

Example 3
int a = 6; 
int b = 4; 

Console.WriteLine(a > b ? "a is greater than b" : "a is less than b");
Console.WriteLine(a < b ? "a is greater than b" : "a is less than b");

b = 6; 
Console.WriteLine(a == b ? "a is equal to b" : "a is not equal to b");
Console.WriteLine(a != b ? "a is equal to b" : "a is not equal to b");
Console.WriteLine((6+2 == 8) ? 8 : 6);
OUTPUT

a is greater than b
a is less than b
a is equal to b
a is not equal to b
8

Run Demo

Pirzada Rashid

Senior .NET developer with a Master of Science in Information Technology.
Teaching is one of my passions. It gives me great joy to share my knowledge with others, and I look forward to investing more energy into it.

Add Comment

Click here to post a comment

Popular Video

82,490+ Views