Naphtali Davies
Naphtali Davies

Reputation: 227

cast short to int in if block

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 ?

Upvotes: 8

Views: 544

Answers (4)

Avi Turner
Avi Turner

Reputation: 10456

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.

Upvotes: 0

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

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;

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125650

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

Upvotes: 1

Adam Houldsworth
Adam Houldsworth

Reputation: 64517

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.

Upvotes: 7

Related Questions