Sum of Two Short types in C#

Shervan360 1,481 Reputation points


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!

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,487 questions
{count} votes

Accepted answer
  1. Viorel 113.8K Reputation points

    According to “CSharp Language Specification” (Section 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