Many people may not notice that the processing of the byte type in C # is quite special.
Below I will use a few simple lines of code to illustrate the problem
Byte x = 1;
Byte y = 2;
Byte z = x + y; // error: the int type cannot be converted to the byte type.
Many may think that this code is correct. In fact, the third row produces a compilation error: the int type cannot be converted to the byte type!
Why? Because the C # compiler considers the result of byte and byte operations to be int type, the short type is actually processed similarly.
In my opinion, the reason for this design is that byte or short type operations are prone to overflow, so we can convert them to int for calculation.
Let's look at the following code.
Byte I = 1; // OK
The literal value 1 is recognized by the compiler as the int type. In the preceding statement, the integer1SlaveIntImplicit type conversionByteType. If the integer exceedsByteType range, a compilation error will occur.
The above is the description in MSDN. In fact, this implicit conversion violates the rule that a type with a small range can be implicitly converted to a type with a large range. However, in C #, this conversion is true.
Note that this conversion is only true when the literal value of an integer is used for the value assignment operation, as this is not the case:
Int x = 1;
Byte I = x; // error: the int type cannot be converted to the byte type.
Check the following code:
Byte I = 1;
I + = 1; // OK
This line of code can be passed because x + = y in C # is not always equivalent to x = x + y!
If the result type of x + y can be implicitly converted to the x type, then x + = y is equivalent to x = x + y.
If the result type of x + y can be explicitly converted to the x type, and x = y is also valid, then x + = y is equivalent to x = (T) (x + y), where T is the x type.
Like the above Code, I + 1 is of the int type and can be explicitly converted to the byte type, while I = 1 is also valid, so I + = 1 is equivalent to I = (byte) (I + 1)
I = I + 1; // error: the int type cannot be converted to the byte type.
This line is easy to understand. 1 is recognized by the compiler as the int type, so the result of I + 1 is of the int type and cannot be converted to the byte type.