What is ternary operator in C#?



Ternary operator is a Conditional operator in C#. It takes three arguments and evaluates a Boolean expression.

For example −

y = (z == 1) ? 100 : 180;

Above, if the first operand evaluates to true (1), the second operand is evaluated. If the first operand evaluates to false (0), the third operand is evaluated.

The following is an example −

Example

using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         int x, y;
         x = 25;
         y = (x == 25) ? 20 : 30;
         Console.WriteLine("Value of x = {0}", y);

         y = (x == 1) ? 50 : 90;
         Console.WriteLine("Value of y = {0}", y);

         Console.ReadLine();
      }
   }
}

Above we have two conditions using the ternary operators −

y = (x == 25) ? 20 : 30;
y = (x == 1) ? 50 : 90;
Updated on: 2020-06-20T16:53:30+05:30

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements