C# Ternary Operator

Question and answer

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

Ternary expression initialization

Note

One common use of the ternary operator in the C# language and other C-like languages 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'.

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 but simplifies the high-level representation of the branching at the level of the source code.

This C# program shows how to use ternary statements. The ternary operator can replace an if-statement.

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

Overview. The program above shows how the ternary expression can be used when initializing a variable. If the subexpression (100.ToString() == "100") 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 ternary expression

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. The intermediate language generated is equivalent to an if-statement being used instead, 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

Returning expressions. The above program text invokes the GetValue method twice in the Main entry point. The GetValue method internally executes the intermediate language branching instructions that are equivalent to the logic expressed in the high-level ternary operator. If the parameter to GetValue is equal to the string data in the literal, the integer literal 100 is returned. Otherwise, the integer literal of -1 is returned.

Ternary min and 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, but the Math class in the .NET Framework provides the Math.Min and Math.Max methods, which handle certain cases more effectively and may have clearer calling syntax.

The decimal type in the .NET Framework is handled separately by the Math.Max and Math.Min methods, and for this type the ternary expression may not be equivalent.

Math.Min Math.Max

Implementation

.NET Framework information

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, as in it tests that the subexpression is false instead of testing if it is true. This reorders some of the instructions and can occasionally boost performance.

Summary

The C# programming language

We looked at the ternary operator in the C# programming language, using it to initialize an integer variable and then using it to return a value. We noted that the ternary statement can receive an expression that it first evaluates before proceeding to part after the question mark. We reviewed some aspects of the intermediate language and some additional uses of the ternary statement and how it can produce branches in your control flow.

If Statement
.NET