C# Ternary Operator

Use ternary statements to replace if-statements with shorter and more readable code.
Ternary operator. The ternary operator tests a condition. It compares 2 values. 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.If

Tip: It does not eliminate branching. It simplifies the high-level representation of the branching.

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.IL

Here: If the subexpression 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.

C# program that uses ternary operator 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
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.

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.

C# program that returns ternary expression 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
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.

C# program that causes implicit conversion error class Program { static void Main() { int temp = 200; int value = temp == 200 ? "bird" : 0; } } Output 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.

Null Coalescing
C# program that uses ternary, null coalescing 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); } } Output 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 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.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 subexpression 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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls