C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: It does not eliminate branching. It simplifies the high-level representation of the branching.
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
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
Tip: To fix ternaries with this error, try adding casts to the 2 result values so they have the same type.
CastsC# 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'
So: We can replace ternaries that test null with a null coalescing statement that uses the "??" operator.
Null CoalescingC# 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
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, MinDifference: 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.