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

CsharpProgrammingServer Side Programming

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.

Example

 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);
         Console.ReadKey();
      }
   }
}

Output

Number One = 100
Number Two = 200
raja
Published on 18-Sep-2018 16:20:13
Advertisements