Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast short to int in if block

Tags:

c#

casting

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 ?

like image 327
Naphtali Davies Avatar asked Aug 08 '13 11:08

Naphtali Davies


Video Answer


2 Answers

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.

like image 148
Adam Houldsworth Avatar answered Oct 06 '22 00:10

Adam Houldsworth


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);
like image 21
MarcinJuraszek Avatar answered Oct 05 '22 23:10

MarcinJuraszek