Why are there no arithmetic operators (+, -, *, /,%) for 8 and 16 bit integers in C #?

I was shocked to know that there are no arithmetic operators + , - , * , / and % for 8 and 16 bit integers in C #. I read β€œC # 5.0 Pocket Reference” on page 23 as follows.

enter image description here

The following code does not compile.

 class Program { static void With16Bit() { short a = 1; short b = 2; short c = a + b; Console.WriteLine(c); } static void With8Bit() { byte a = 1; byte b = 2; byte c = a + b; Console.WriteLine(c); } static void Main(string[] args) { With8Bit(); With16Bit(); } } 

Why did C # designers do this? What is their opinion on this?

+7
c #
source share
3 answers

There are arithmetic with Int8 , Int16 ; but the result is int32 , so you need to do:

 class Program { static void With16Bit() { short a = 1; short b = 2; short c = (short) (a + b); // <- cast, since short + short = int Console.WriteLine(c); } static void With8Bit() { byte a = 1; byte b = 2; byte c = (byte) (a + b); // <- cast, since byte + byte = int Console.WriteLine(c); } static void Main(string[] args) { With8Bit(); With16Bit(); } } 
+9
source share

Mixed, remember that when you perform the add operation on short and byte , the default result is Integer.

So:

byte + byte = int
short + short = int

So, if you want to return the actual value you need to return.

Try the following:

  short a = 1; short b = 2; short c =(short) (a + b); Console.WriteLine(c); byte a = 1; byte b = 2; byte c =(byte) (a + b); Console.WriteLine(c); 

From Source :

This behavior is explained by the fact that the designers did not consider that byte and short as real numbers, but they considered them as just a sequence of bits . therefore, performing arithmetic operations on them makes no sense, so if so, then int and long serve the purpose.

+5
source share

From answer kek444

 All operations with integral numbers smaller than Int32 are widened to 32 bits before calculation by default. The reason why the result is Int32 is simply to leave it as it is after calculation. If you check the MSIL arithmetic opcodes, the only integral numeric type they operate with are Int32 and Int64. It "by design". 
+2
source share

All Articles