Sum of Two Short types in C#

Shervan360 1,661 Reputation points
2023-05-13T15:39:08.48+00:00

Hi,

Why do we have an error in the sum of two short types? But not in Int types.

using System.Numerics;

namespace ConsoleApp3;
internal class Program
{
    static void Main(string[] args)
    {
        short x = 1, y = 1;
        short z = x + y; //// Compile-time error

        int a = 1, b = 1;
        int c = a + b; //// No error!
    }
}


Developer technologies | C#
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-05-13T16:47:02.7233333+00:00

    According to “CSharp Language Specification” (Section 7.3.6.2 Binary numeric promotions), both short operands of your code are converted to type int. The “+” operator is not defined separately for short. It works for int and the result is int. Therefore, the result should be converted to short (for example: short z = (short)(x + y)). Errors are possible if the result cannot be short.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.