Ternary operator in C#:
The ternary operator is a decision-making operator. It is also called conditional operator. Based on a condition, it executes one statement. In this post, I will show you how to use ternary operator in C# with examples.
Syntax of ternary operator:
Below is the syntax of ternary operator:
condition ? first-statement : second-statement
The condition returns true or false. If it is true, it executes the first-statement, else it will execute second-statement.
It looks as like below for if-else:
if(condition) {
first-statement
}else{
second-statement
}
Example of ternary operator:
Let’s write a simple odd-even-checker program using if-else and then convert it to ternary operator.
Using if-else:
using System;
public class Program
{
public static void Main()
{
int no = 40;
if(no % 2 == 0){
Console.WriteLine("Entered number is even");
}else{
Console.WriteLine("Entered number is odd");
}
}
}
The same program can be written as:
using System;
public class Program
{
public static void Main()
{
int no = 40;
Console.WriteLine(no % 2 == 0 ? "Entered number is even" : "Entered number is odd");
}
}
Both programs will print the same output:
Entered number is even