Home
Map
Ternary OperatorUse ternary statements to replace if-statements with shorter and more readable code.
C#
This page was last reviewed on Sep 11, 2023.
Ternary. 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.
Note It has its location on the stack copied to the binary representation of -1.
Note 2 This code uses branch statements that are defined in the intermediate language.
using System; // 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.
Detail 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.
Cast
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; 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.
Detail This type is handled separately by the Math.Max and Math.Min methods. The ternary expression may not be equivalent.
Math.Max, Math.Min
Implementation. I disassembled several versions of ternary expressions and found that they are identical to if-statements, with one small difference.
Detail 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.
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.
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.
This page was last updated on Sep 11, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.