C# Ternary Operator

Just like If statements, C# Ternary operator tests a condition and initializes a variable with the result of the condition.

C# Ternary Operator Syntax

<condition> ? <expression1> : <otherwise expression 2>;

If the condition is satisfied Ternary operator returns expression 1; otherwise, it returns expression 2. Let us see an example using a C# Conditional operator.

Example C# code using If else statement

using System;
 
 class Ternary_Operators
 {
   static void Main()
   {
     int number = 15;
 
     bool Isnumber15;
 
     if(number == 15)
     {
       Isnumber15 = true;
     }
     else
     {
       Isnumber15 = false;
     }
     
     Console.WriteLine("Number == 15 is {0}", Isnumber15);
   }
 }

OUTPUT

C# Ternary operator 1

ANALYSIS

Here, number is an integer variable initialized with 15. Isnumber15 is a Boolean variable to store the result.

I was checking whether number == 15 using if condition. If the condition is satisfied, then Isnumber returns true else Isnumber returns false.

Here, Isnumber = true printed on to the C# console.

C# Ternary Operator Example

It is the same example that we specified in the above. However, this time, we are using the C# Ternary operator. The ternary operator returns the result of the statement, and it will not execute the statement.

It returns the value of any data type.

C# code using Conditional operator

using System;
 
 class Ternary_Operators
 {
   static void Main()
   {
     int number = 15;
 
     bool Isnumber15 = number == 15 ? true : false;
      
     Console.WriteLine("Number == 15 is {0}", Isnumber15);
   }
 }

OUTPUT

C# Ternary operator 2

ANALYSIS

Using the ternary operator reduces the size of the code too much smaller.

In the above c# conditional operator code, we have collected the result of a statement into a boolean variable Isnumber 15. And the result is printed.

Instead of collecting into a variable, we can even directly print i.e., in the above code

bool Isnumber15 = number == 15 ? true : false;

Console.WriteLine(“Number == 15 is”, Isnumber15); 

Instead of writing in two lines, we can write as follows:

Console.WriteLine(number == 15 ? true : false);