C# Ternary Operator

Question and answer

The ternary operator tests a condition. It compares two values. It produces a third value that depends on the result of the comparison. This can be accomplished with if-statements or other constructs.

Tip:The ternary operator provides an elegant and equivalent syntax form to the if-statement.

Example

Question

One common use of the ternary operator is to initialize a variable with the result of the expression. At compile-time, the C# compiler translates the ternary expression into branch statements such as brtrue.

Intermediate Language

However, the high-level ternary statement is useful because it allows you to condense multiple if-statements and reduce nesting. It does not actually eliminate branching. It simplifies the high-level representation of the branching.

Program that uses ternary operator: C#

using System;

class Program
{
    static void Main()
    {
	//
	// If the expression is true, set value to 1.
	// Otherwise, set value to -1.
	//
	int value = 100.ToString() == "100" ?
	    1 :
	    -1;

	Console.WriteLine(value);
    }
}

Output

1
True keyword

The program uses the ternary expression to initialize a variable. If the subexpression evaluates to true, the integer variable with the identifier 'value' has its location on the stack copied to the bit values of the integer 1.

Otherwise:It has its location on the stack copied to the binary representation of -1.

Internally:This code uses branch statements that are defined in the intermediate language.

Return

Return keyword

You can return the result of a ternary statement in a method return statement. The result of evaluating the ternary operator must match the return type of the enclosing method for the compilation to succeed.

Note:The intermediate language generated is equivalent to an if-statement, but the source code contains fewer lines of code.

Program that returns ternary expression: C#

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine(GetValue("Sam"));
	Console.WriteLine(GetValue("Jane"));
    }

    /// <summary>
    /// Return the value 100 if the name matches, otherwise -1.
    /// </summary>
    static int GetValue(string name)
    {
	return name == "Sam" ? 100 : -1;
    }
}

Output

100
-1
Main method

We invoke the GetValue method twice in the Main method. The GetValue method internally executes the intermediate language branching instructions that are equivalent to the logic expressed in the high-level ternary operator.

And:If the parameter to GetValue is equal to the string data in the literal, the integer 100 is returned. Otherwise -1 is returned.

Min, max

Programming tip

One popular use of the ternary operator in C-like languages is to get the minimum or maximum of two numbers or one variable and an integer constant. This approach is still useful in the C# language.

Note:The Math class in the .NET Framework provides the Math.Min and Math.Max methods. These have clearer calling syntax.

Decimal:This type is handled separately by the Math.Max and Math.Min methods. The ternary expression may not be equivalent.

Math.MinMath.Max

Implementation

Framework: NET

I disassembled several versions of ternary expressions and found that they are identical to if-statements, with one small difference. The ternary statement sometimes produces code that tests the opposite condition that you would expect.

And:It tests that the subexpression is false instead of testing if it is true. This reorders some of the instructions.

Summary

The C# programming language

We looked at the ternary operator. We used it to initialize an integer variable and then used it to return a value. The ternary statement can receive an expression that it first evaluates before proceeding to part after the question mark.

And:We investigated parts of the intermediate language. We saw some additional uses of the ternary statement.


C#: If