I have the following code:
Int16 myShortInt;
myShortInt = Condition ? 1 :2;
This code results in a compiler error:
cannot implicity convert type 'int' to 'short'
If I write the condition in the expanded format there is no compiler error:
if(Condition)
{
myShortInt = 1;
}
else
{
myShortInt = 2;
}
Why do I get a compiler error ?
You get the error because literal integer numbers are treated as int by default and int does not implicitly cast to short because of loss of precision - hence the compiler error. Numbers featuring a decimal place, such as 1.0 are treated as double by default.
This answer details what modifiers are available for expressing different literals, but unfortunately you cannot do this for short:
C# short/long/int literal format?
So you will need to explicitly cast your int:
myShortInt = Condition ? (short)1 :(short)2;
Or:
myShortInt = (short)(Condition ? 1 :2);
short to a short:
myShortInt = 1;
Not sure why that wasn't extended to ternary actions, hopefully someone can explain the reasoning behind that.
Plane numbers like 1 and 2 are treated as integers by default, so your ?: returns an int, which has to be converted into short:
Int16 myShortInt;
myShortInt = (short)(Condition ? 1 :2);
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