Short and arithmetic operations

How arithmetic operators convert short values when performing operations

Home DailyDrop

Daily Knowledge Drop

When performing arithmetic operations on short data types, their values are converted to the int types, which is also the type of the result of the operation.


Examples

When working with integral types which could be an int or short, the compiler will infer int:

// the compiler will infer than intValue is 
// an int (even though it could be a short)
// in this specific example
var intValue = 32 / 2;

However, when specifying the variable type explicitly, the compiler will infer the value as a short:

short shortValue = 32 / 2;

Here the value 32 is inferred as a short, and the output of the operator is explicitly declared as a short.

All good so far - but now is where the are a bit unexpected.

Operations on an explicitly defined short value, will result in a int result

// short value is definitely a short
short shortValue = 32 / 2;

// int response, all good
int intOutput = shortValue / 2;

// ERROR: this gives a compiler error
//short shortOutput = (shortValue / 2);

In the last operation, even though it is being performed on a short value, the result is an int and the above results in the error:

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

Thankfully, the error is very easy to resolve - as the error states, an explicit conversion needs to be done:

// All good!
short shortOutput = (short)(shortValue / 2);

Notes

A small quirk of the language, which if encountered just needs to be managed and handled. Before being aware of this knowledge, I would have assumed that a short would be returned from an operation where the operands were defined as short - this assumption would be incorrect though!


References

Reddit Post

Daily Drop 213: 30-11-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net short operator