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.
static void Main()
/// Return the value 100 if the name matches, otherwise -1.
static int GetValue(string name)
return name == "Sam" ? 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.
static void Main()
int temp = 200;
int value = temp == 200 ? "bird" : 0;
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.
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
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.