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

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.


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

Read Eric Lippert 's answers to these questions

  • Integer summing blues, short += short problem
  • Unary minus on a short becomes an int?

Adding two Int16 values result in an Int32 value. You will have to cast it to Int16:

Int16 answer = (Int16) (firstNo + secondNo);

You can avoid this problem by switching all your numbers to Int32.


The problem is, that adding two Int16 results in an Int32 as others have already pointed out.
Your second question, why this problem doesn't already occur at the declaration of those two variables is explained here: http://msdn.microsoft.com/en-us/library/ybs77ex4%28v=VS.71%29.aspx:

short x = 32767;

In the preceding declaration, the integer literal 32767 is implicitly converted from int to short. If the integer literal does not fit into a short storage location, a compilation error will occur.

So, the reason why it works in your declaration is simply that the literals provided are known to fit into a short.