By 22/07/2015 13 Comments

C# Conditional ?: Operator

  • It is denoted by (?) symbol and called Ternary operator (?).
  • It is also called conditional operator because it executes on condition.
  • It is a shorthand form of (if….else) statement.


(Condition or bool expression) ? expression_1: expression_2;


int number = 1;

(Condition or bool expression) It can be any bool expression such as (number == 1), we can also use logical operators in this condition such as (number == 1 || number ! = 1).
? This question mark symbol specifies the separation of (Condition or bool expression) from expression_1 and expression_2.
expression_1 It is a first expression which will be performed or executed when condition becomes true.
: Colon, this colon symbol specifies the separation of expression_1 from expression_2.
expression_2 It is a second expression which will be performed or executed when condition becomes false.


  • The type of expression_1 and expression_2 and a variable which will be used for assigned must be the same type (or, an implicit conversion between them must exist).
  • You should use ternary operator instead of if….else because ternary or conditional operator is faster than if….else.


using System;
namespace csharpBasic
  // Start class definition / declaration.
    class Program
      // Static main method void type declaration.
        static void Main(string[] args)
            // Following declare and initialize an int type variable number with 1 value.
            int number = 1;

            // Following declare a bool type variable result.
            bool result;

            // Use of conditional/ternary operator, assign it into result.
            result = (number == 1 || number != 1) ? true : false;

            // Print result variable.
            Console.WriteLine("Ternary operator with logical operator: " + result);

            result = (number == 1) ? true : false;
            Console.WriteLine("Ternary operator without logical operator: " + result);

            // string type variable declaration.
            string resultMessage;

            resultMessage = (number != 1) ? "Number is not 1" : "Number is 1";

        } // End of main method definition.

    } // End of class.

Next Tutorial →

← Previous Tutorial

Posted in: C# Basics, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .