Facebook Page Twitter Page LinkedIn Page
× C# Tutorial C# Advanced C# Resources


The C# conditional or ternary operator returns one of the two values based on the value of boolean expression. It is kind of similar to the if-else statement and helps to write the if-else statements in a short way.

Syntax

//returns value1 if expression is true
//returns value2 if expression is false
expression ? value1 : value2

Return Value

Returns value1 if the expression is evaluated to be true, and value2 if the expression is evaluated to be false.

Example:

In the below example, the ternary operator is used to find out the maximum of two numbers.

using System;

class MyProgram {
  static void Main(string[] args) {
    int x = 50;
    int y = 100;

    //maximum of two value
    int max = (x > y) ? x : y;

    //displaying the result
    Console.WriteLine("Maximum value = "+ max);
  }
}

The output of the above code will be:

Maximum value = 100

❮ C# - Operators

5