Home
Search
Ternary OperatorUse ternary statements to replace if-statements with shorter and more readable code.
C#
This page was last reviewed on Oct 27, 2022.
Ternary operator. The C# ternary operator tests a condition. It compares 2 values. And it produces a third value that depends on the result of the comparison.
Operator notes. The ternary effect can be accomplished with if-statements or other constructs. The ternary operator provides an elegant and equivalent syntax form to the if-statement.
If
An example. One use of a ternary is to initialize a variable with the result of the expression. The C# compiler translates the ternary expression into branch statements such as brtrue.
Here If the expression evaluates to true, the int "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.
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); } }
1
Return. You can return the result of a ternary statement. The result of evaluating the ternary operator must match the return type of the enclosing method for the compilation to succeed.
Return
Note The intermediate language generated is equivalent to an if-statement, but the source code contains fewer lines of code.
GetValue This executes the 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.
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; } }
100 -1
Implicit conversion error. The two result values of a ternary must have implicit conversions to the same type. Here we cannot cast a string to an int in a ternary, so we get an error.
Tip To fix ternaries with this error, try adding casts to the 2 result values so they have the same type.
Casts
class Program { static void Main() { int temp = 200; int value = temp == 200 ? "bird" : 0; } }
Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'int'
Ternary, null coalescing. For certain ternary statements, a null coalescing operator can be used instead. This operator tests for null, and if the value is null, we can specify the value.
So We can replace ternaries that test null with a null coalescing statement that uses the "??" operator.
using System; class Program { static void Main() { string temp = null; // Use null coalescing syntax to initialize a value. string value1 = temp ?? "bird"; Console.WriteLine("NULL COALESCING: " + value1); // Use ternary for same result. string value2 = temp == null ? "bird" : temp; Console.WriteLine("TERNARY: " + value2); } }
NULL COALESCING: bird TERNARY: bird
Min, max. One use of the ternary operator 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 .NET 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.Max, Min
Implementation. I disassembled several versions of ternary expressions and found that they are identical to if-statements, with one small difference.
Difference The ternary statement sometimes produces code that tests the opposite condition that you would expect.
And The ternary tests that the expression is false instead of testing if it is true. This reorders some of the instructions.
A summary. We used a ternary to initialize an int and then to return a value. We investigated parts of the intermediate language. We saw some additional uses of the ternary statement.
IL
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.