The C# ternary operator tests a condition. It compares two values, and it produces a third value that depends on the result of the comparison.
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.
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.
int
"value" has its location on the stack copied to the bit values of the integer 1.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
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.
if
-statement, but the source code contains fewer lines of code.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
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.
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'
null
coalescingFor 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.
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
, maxOne 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.
class
in .NET provides the Math.Min
and Math.Max
methods—these have clearer calling syntax.Math.Max
and Math.Min
methods. The ternary expression may not be equivalent.I disassembled several versions of ternary expressions and found that they are identical to if
-statements, with one small difference.
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.