Using C# ternary with String.Equals

short value;
value = 10 > 4 ? 5 : 10;             //1
value = "test" == "test" ? 5 : 10;   //2
string str = "test";
value = "test" == str ? 5 : 10;      //3
value = "test".Equals(str) ? 5 : 10; //4

The last two ternary expressions (3,4) cannot be resolved to a constant at compile time. Thus the compiler treats the 5 and 10 as int literals, and the type of the entire ternary expression is int. To convert from an int to a short requires an explicit cast.

The first two ternary expressions (1,2) can be resolved to a constant at compile time. The constant value is an int, but the compiler knows it fits in a short, and thus does not require any casting.

For fun, try this:

value = "test" == "test" ? 5 : (int)short.MaxValue + 1;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)