Ternary operator in C#

(Last Updated On: January 29, 2019)

Ternary operator C# example-Learn how to compare two values using ternary operator (? : ) and how to execute the statement with explanation and example programs.

When ever we want to compare 2 values, we can do with the if else statement as shown below.

In the same way whenever we want to compare 2 values, we can also do with a special decision making operator called ternary operator i.e (? : ) which is similar to if-else.

Syntax:

Condition is the boolean expression.
statement1 is evaluated if condition is true and statement2 is evaluated if condition is false.

 

C# Ternary Operator Example

c# code

Output:
result using if else condition : a is less than b
result using ternary operator : a is less than b

 

NOTE:
Ternary operator makes the code shorter. There is no performance difference between Ternary operator and if – else.
use ternary operator only if the code is one liner and no change in the code in future. other wise use if -else.