C# Ternary Operator

Just like If statements, the C# Ternary operator tests a condition and initializes a variable with the result of the condition. The 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 or Ternary operator. An example code using theIf 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, the number is an integer variable initialized with 15. Isnumber15 is a Boolean variable to store the result.

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

Here, Isnumber = true printed onto the C# console.

C# Ternary Operator Example

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

It returns the value of any data type.

The code uses a 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 to much smaller.

In the above code, we have collected the result of a statement into a boolean variable Isnumber 15. And the result will print.

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);
Categories C#