How to use the ?: conditional operator in C#?

A conditional operator is represented by the symbol '?:' The first operand is the evaluating expression. It has right to left associativity.

The syntax for conditional operator.

expression ? expression : expression

The conditional operator works as follows −

  • The first operand is implicitly converted to bool.

  • If the first operand evaluates to true, the second operand is evaluated.

  • If the first operand evaluates to false, the third operand is evaluated.

Remember, only one of the last two operands is evaluated in a conditional expression.


 Live Demo

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         int num1 = 100, num2;
         num2 = ( num1 ==100 ? 200 : 0 ) ;
         Console.WriteLine("Number One = "+num1);
         Console.WriteLine("Number Two = "+num2);


Number One = 100
Number Two = 200

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started