C# Conditional Operator

The syntax of C# Conditional Operator ?: is shown below.

Condition ? Expression 1 : Expression 2
  • If Condition is true, Expression 1 is returned.
  • If Condition is false, Expression 2 is returned.
  • The type of Expression 1 and Expression 2 should be the same. If not, one must be implicitly converted to the other.
  • The sequence of the calculation is from right to left.

Example 01-13-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;

namespace TestConditionalOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            int mark = 70;
            string result;
			
            result = mark >= 60 ? "Passed" : "Not Passed";
            Console.WriteLine("Your mark is {0} - {1}", mark, result);

            mark = 55;
            result = mark >= 60 ? "Passed" : "Not Passed";
            Console.WriteLine("Your mark is {0} - {1}", mark, result);
			
            mark = 95;
            result = mark < 90 ? "below A" : mark < 95 ? "A" : "A+";
            Console.WriteLine("Your mark is {0} and you are {1}", mark, result);
			
            mark = 91;
            result = mark < 95 ? mark < 90 ? "below A" : "A" : "A+";
            Console.WriteLine("Your mark is {0} and you are {1}", mark, result);
            Console.Read();
        }
    }
}

Output

Your mark is 70 - Passed
Your mark is 55 - Not Passed
Your mark is 95 and you are A+
Your mark is 91 and you are A
  • Line 9: Initialize int variable mark as 70.
  • Line 12: Firstly check the condition mark >= 60 value, it returns true so "Passed" is assigned to variable result.
  • Line 13: Output Passed.
  • Line 15: 55 is assigned to mark.
  • Line 16: Evaluate mark >= 60 and it is false, so "Not Passed" is returned;
  • Line 19: 95 is assigned to mark.
  • Line 20: Because the associativity of ?: operator is from right to left. mark < 95 ? "A" : "A+" is calculate first and returned "A+". Then the whole is equivalent to result = mark < 90 ? "below A" : "A+"; then evaluate mark < 90 and get false, so the whole result is "A+".
  • Line 23: 91 is assigned to mark.
  • Line 24: We'll evaluate mark < 90 ? "below A" : "A" first and get "A". The whole expression is changed to result = mark < 95 ? "A" : "A+"; Then mark < 95 return true so "A" is returned.
  • Line 25: Output the result.