Doing Arithmetic Operations With 8-bit and 16-bit Integral Types in C#

Sorin Subulescu
1 min readSep 16, 2019

--

In C#, the 8-bit integral types are byte and sbyte and the 16-bit ones are short and ushort. These types lack their own arithmetic operators, so C# automatically converts them to larger integral types, so that the operations could be performed.

For example, let’s take the following lines of code:

short a = 1, b = 2;
short c = a + b; //This assignment will throw a compile time error

In the first line, we create two variables of type short, a and b. We assign them the values of 1 and 2. On the next line, we create a new short variable, c, and try to assign it the sum of a and b. Our instinct tells us that everything should work fine here, but as soon as you try to compile this code, it will throw an error. Why is this happening?

The compiler implicitly converts a and b to int so that the addition can be performed. This means that the result will also be an int, which can’t be implicitly cast to short.

To resolve this problem, we need to add an explicit cast:

short c = (short)(a + b);

--

--