Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the result of a subtraction of an Int16 parameter from an Int16 variable an Int32? [duplicate]

Tags:

variables

c#

.net

Possible Duplicate:
byte + byte = int… why?

I have a method like this:

 void Method(short parameter)
 {
     short localVariable = 0;
     var result = localVariable - parameter;
 }

Why is the result an Int32 instead of an Int16?

like image 904
Jader Dias Avatar asked Jul 05 '09 19:07

Jader Dias


1 Answers

It's not just subtraction, there simply exisits no short (or byte/sbyte) arithmetic.

short a = 2, b = 3;
short c = a + b;

Will give the error that it cannot convert int (a+b) to short (c).

One more reason to almost never use short.

Additional: in any calculation, short and sbyte will always be 'widened' to int, ushort and byte to uint. This behavior goes back to K&R C (and probaly is even older than that).

The (old) reason for this was, afaik, efficiency and overflow problems when dealing with char. That last reason doesn't hold so strong for C# anymore, where a char is 16 bits and not implicitly convertable to int. But it is very fortunate that C# numerical expressions remain compatible with C and C++ to a very high degree.

like image 65
Henk Holterman Avatar answered Oct 19 '22 23:10

Henk Holterman