When I write this code in VS, it doesn't work ("Cannot implicitly convert 'int' to 'short'. An explicit conversion exists. Are you missing a cast?"):
short A = 5;
short B = 1 << A;
Yet this code is absolutely fine:
short A = 1 << 5;
I know I can make the error go away by casting the entire expression as a short, but can anyone tell me why this happens?
Because A is not a literal, the compiler doesn't know that the result is representable as a short
. Therefore it needs an explicit cast. With the literal 5, the compiler sees that the result is 32, which can fit in a short
.
The C# Language specification 4.0 states in 6.1.9:
A constant-expression (§7.18) 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.
Conversion of constant expressions is one of the special cases where this will be implicit (6.1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With