8

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 ?

Joe Vi
  • 473
  • 4
  • 10
Naphtali Davies
  • 227
  • 1
  • 9

4 Answers4

7

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);


There are cases when the compiler can do this for you, such as assigning a literal integer value that fits inside a short to a short:
myShortInt = 1;

Not sure why that wasn't extended to ternary actions, hopefully someone can explain the reasoning behind that.

Community
  • 1
  • 1
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
  • `unfortunately you cannot do this for short` Damnit... I was so sure there was something like `1s` for short... Oh well, +1 for the answer. – Nolonar Aug 08 '13 at 11:25
1

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);
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

You could write:

Int16 myShortInt;  
myShortInt = Condition ? (short)1 : (short)2;

or

myShortInt = (short) (Considiton ? 1 : 2);

but yeah, as Adam already answered C# considers whole number literals as ints except in the super simple cases like the one you stated:

short x = 100;
Kevin DiTraglia
  • 25,746
  • 19
  • 92
  • 138
0

When the code is being compiled, It looks something like this:

for:

Int16 myShortInt;  
 myShortInt = Condition ? 1 :2;

It looks somthing like

Int16 myShortInt; 
var value =  Condition ? 1 :2; //notice that this is interperted as an integer.
myShortInt = value ;

while for:

if(Condition)  
{  
 myShortInt = 1;  
}  
else  
{  
 myShortInt   = 2;  
} 

There is no stage in between to interperate the value as int, and the literal is being treated as a Int16.

Avi Turner
  • 10,234
  • 7
  • 48
  • 75
  • I'm guessing the ternary operator is generic; something like `public T operator ?: (bool condition, T a, T b)` and the compiler believes that `T` in this instance is an `int`, because both inputs are `int`s. – Nolonar Aug 08 '13 at 11:39