Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'int' to 'short' [duplicate]

Tags:

c#

int

short

I wrote the following small program to print out the Fibonacci sequence:

static void Main(string[] args) {     Console.Write("Please give a value for n:");     Int16 n = Int16.Parse(Console.ReadLine());      Int16 firstNo = 0;     Int16 secondNo = 1;      Console.WriteLine(firstNo);     Console.WriteLine(secondNo);      for (Int16 i = 0; i < n; i++)     {         //Problem on this line                             Int16 answer = firstNo + secondNo;          Console.WriteLine(answer);          firstNo = secondNo;         secondNo = answer;     }      Console.ReadLine();  } 

The compilation message is:

Cannot implicitly convert type 'int' to 'short'. An explicit conversion exists (are you missing a cast?)

Since everything involved is an Int16 (short) then why are there any implicit conversions going on? And more specificially why the failure here (and not when initially assigning an int to the variable)?

An explanation would be much appreciated.

like image 545
m.edmondson Avatar asked May 04 '11 11:05

m.edmondson


People also ask

How do you convert int to int?

For converting Integer to int in Java explicitly, you can utilize the “intValue()” method of the Java “Integer” class. It takes no arguments and gives a primitive value as an output.

What is the use of INT in C#?

int is a keyword that is used to declare a variable which can store an integral type of value (signed integer) the range from -2,147,483,648 to 2,147,483,647. It is an alias of System.


2 Answers

Microsoft converts your Int16 variables into Int32 when doing the add function.

Change the following:

Int16 answer = firstNo + secondNo; 

into...

Int16 answer = (Int16)(firstNo + secondNo); 
like image 67
myermian Avatar answered Sep 30 '22 05:09

myermian


Read Eric Lippert 's answers to these questions

  • Integer summing blues, short += short problem
  • Unary minus on a short becomes an int?
like image 40
abhilash Avatar answered Sep 30 '22 06:09

abhilash