0
0
C Sharp (C#)programming~5 mins

Ternary conditional operator in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The ternary conditional operator lets you choose between two values quickly based on a condition. It makes your code shorter and easier to read when you have simple decisions.

When you want to assign a value based on a simple yes/no question.
When you want to print different messages depending on a condition.
When you want to return one of two values from a method quickly.
When you want to replace a short if-else statement with cleaner code.
Syntax
C Sharp (C#)
condition ? value_if_true : value_if_false;
The condition is a boolean expression that is either true or false.
If the condition is true, the operator returns value_if_true, otherwise it returns value_if_false.
Examples
Assigns the greater of a or b to max.
C Sharp (C#)
int max = (a > b) ? a : b;
Sets result to "Pass" if score is 60 or more, otherwise "Fail".
C Sharp (C#)
string result = (score >= 60) ? "Pass" : "Fail";
Prints a message depending on whether isSunny is true or false.
C Sharp (C#)
Console.WriteLine(isSunny ? "Take sunglasses" : "Take umbrella");
Sample Program

This program checks if age is 18 or more. If yes, it sets canVote to "Yes", otherwise "No". Then it prints the result.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int age = 20;
        string canVote = (age >= 18) ? "Yes" : "No";
        Console.WriteLine($"Can vote: {canVote}");
    }
}
OutputSuccess
Important Notes

The ternary operator is best for simple conditions. For complex logic, use if-else statements for clarity.

Both value_if_true and value_if_false should be of compatible types.

Summary

The ternary operator is a shortcut for if-else that returns one of two values.

It uses the syntax: condition ? value_if_true : value_if_false.

Use it to write shorter and cleaner code for simple decisions.