Ternary Operator in C#


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

For example −

b = (a == 1) ? 20 : 30;

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

 Live Demo

using System;

namespace DEMO {

   class Program {

      static void Main(string[] args) {

         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}

Output

Value of b is 30
Value of b is 20

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements