Site icon

Conditional operator(?:) in C#

Conditional operator (?:) in C# is used as a single line if-else assignment statement, it is also known as Ternary Operator in C#. It evaluates a Boolean expression and on the basis of the evaluated True and False value, it executes corresponding statement.

Precisely, conditional operator (?:) can be explained as follows.

It has three operands: condition, consequence and alternative. The conditional expression returns a Boolean value as true or false . If the value is true, then it evaluates the consequence expression. If false, then it evaluates the alternative expression.

Syntax of conditional operator (?:) in C#

It uses a question mark ( ? ) operator and a colon ( : )  operator , the general format is as follows.

Condition (Boolean expression) ? consequence (if true) : alternative (if false)

Lets look at below example, here we are doing a conditional check and based on the true/false, assigning the variable value to taxPercentage .

bool isSeniorCitizen = true;
int taxPercentage = (isSeniorCitizen) ? 20 : 30;

In above case, If isSiniorCitizen == true then taxPercentage will be 20 else it will be 30, in the above case it sets to 20 since we have already set the boolean value isSiniorCitizen = true .

Example of (?:) operator in C#

Lets look at an example.

using System;
namespace ConditionalOperatorExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string FirstName = "Ramesh";
            string LastName = "";

            //True statement
            string FullName = (String.IsNullOrEmpty(LastName)) ? FirstName : (FirstName + " " + LastName);
            Console.WriteLine(FullName);
        } 
    }
}

In above example code snippet, the boolean expression String.IsNullOrEmpty(LastName) returns True value, so the consequence statement executes, which gives output as “Ramesh” . 

Conditional Operator 1.0

Lets take another example, where conditional expression returns False value.

using System;
namespace ConditionalOperatorExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string FirstName = "Ramesh";
            string LastName = "Kumar";

            //False statement
            string FullName = (String.IsNullOrEmpty(LastName)) ? FirstName : (FirstName + " " + LastName);
            Console.WriteLine(FullName);
        } 
    }
}

In above example, the boolean expression String.IsNullOrEmpty(LastName returns False value, so the alternative statement (FirstName + " " + LastName) executes, which gives output as “Ramesh Kumar”. 

Conditional Operator 1.1

Conditional operator(?:) vs Null Coalescing (??) Operator ?

In the case of Null coalescing operator (??), It checks for the null-ability of first operand and based on that assigns the value. If the first operand value is null then assigns second operand else assigns the first.

Lets have a look at below expression.

x = y ?? z ; // Null Coalescing operator

In the above example, If y is null then z is assigned to x else y . For more details on Null coalescing operator (??), please check here. 

We can rewrite above expression using conditional operator (?:) as follows.

x = (y == null)? z : y ;

Here, if y is null (that means if the expression (Y == null) return true) then assign z else assign y to x .

In single line if else statement:

Lets take below if-else statement.

int i = 5;
int x;

if( i >= 5)
{
    x = 10 * 5;
}
else
{
    x = 10 * 4;
}

In above if-else statement, boolean expression determines variable assignment. This is the right scenario where we can use Conditional operator (?:) as a replacement of if-else statement.

int i = 5;
int x = (i >= 5) ? 10 * 5 : 10 * 4;

In above example, here in this case i >= 5  is a True condition, hence this statement  10 * 5 executes and 50 is assigned to x. Lets take below example.

int i = 3; 
int x = (i >= 5) ? 10 * 5 : 10 * 4;

In above example, here condition i >= 5 is  False, hence 10 * 4  executes and 40 is assigned to x.

Nested conditional operator (?:) in C#

In some scenarios, where there are cascading if-else conditions of variable assignment. We can use chaining conditional operators to replace cascading if-else conditions to a single line, by including a conditional expression as a second statement.

Let’s take below example of cascading/nested if-else statement.

public static decimal CalculateBonusAmount(int SalesLimit)
{
    decimal BonusAmount = 0;
    if (SalesLimit >= 1000)
    {
        BonusAmount = 20000;
    }   
    else if (SalesLimit >= 500)
    {
        BonusAmount = 10000;
    }
    else
    {
        BonusAmount = 5000;
    }
    return BonusAmount;
}

Above cascading if-else condition can be re-written as follows.

public static decimal CalculateBonusAmount(int SalesLimit)
{
     decimal BonusAmount = 0;
 
    //Usage of conditional operator
     BonusAmount = (SalesLimit >= 1000) ? 2000 : (SalesLimit >= 500) ? 10000 : 5000;
     return BonusAmount;
}

Thanks for your time  feel free to provide your feedback and do check my other blogs on Null Coalescing Operator (??) in C#  and  Null-Conditional Operator in C# (?.)

Exit mobile version