Ternary operator behaviour inconsistency [duplicate]
C# language specification, version 5, section 6.1.9:
An implicit constant expression conversion permits the following conversions:
- A constant-expression (§7.19) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.
Your first example is a constant expression, because it can be evaluated at compile time. But see section 7.19 for more details:
Only the following constructs are permitted in constant expressions:
- Literals (including the null literal).
[...]
- The predefined +, –, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, and >= binary operators, provided each operand is of a type listed above.
- The ?: conditional operator.
I believe in the first case the compiler knows that the strings are equal at compile time and therefore optimizes the code to just:
short d = 1;
That works because 1
can be assigned to short
variable.
In the second case optimization cannot happen because compiler cannot infer equality at compile time, so it leaves:
short d = (DateTime.Now == DateTime.Now) ? (long)1 : (long)2;
This will compile:
short d = (DateTime.Now == DateTime.Now) ? (short)1 : (short)2;
IL (LinqPad) for call short d = ("obj" == "obj" ) ? 1 : 2;:
IL_0001: ldc.i4.1
IL_0002: stloc.0 // d