-1

I have this variables inside a class:

 public const ushort HEADER_LENGTH = 5;
 public const ushort CHECKSUM_LENGTH = 2;
 public ushort longitudTrama;
 public ushort longitudTotal;

If I do that:

longitudTotal = longitudTrama;
longitudTotal += HEADER_LENGTH;
longitudTotal += CHECKSUM_LENGTH;

The compiler doesn't generate any error.

But if I do that:

longitudTotal = longitudTrama + HEADER_LENGTH + CHECKSUM_LENGTH;

The compiler says I am missing a cast because it cannot implicitly convert int to ushort. Which int!!??

Thank you.

Charlieface
  • 52,284
  • 6
  • 19
  • 43
Alce
  • 23
  • 6
  • To fix this, you can cast the result of the sum back to ushort as follows: longitudTotal = (ushort)(longitudTrama + HEADER_LENGTH + CHECKSUM_LENGTH); By doing this, you are explicitly telling the compiler to treat the result of the sum as a ushort value, which is the type of longitudTotal. – 山の平和 Mar 11 '23 at 10:12
  • 1
    Thank you. I also want to understand why the sum in the same line gives an int value and why if we do the sum in differents lines it doesn't result in an int. – Alce Mar 11 '23 at 13:04
  • I found the answer at https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators . – Alce Mar 11 '23 at 13:17
  • Because of numeric promotions, the result of the op operation might be not implicitly convertible to the type T of x. In such a case, if op is a predefined operator and the result of the operation is explicitly convertible to the type T of x, a compound assignment expression of the form x op= y is equivalent to x = (T)(x op y), except that x is only evaluated once. – Alce Mar 11 '23 at 13:19
  • In the case of integral types, those operators (except the ++ and -- operators) are defined for the int, uint, long, and ulong types. When operands are of other integral types (sbyte, byte, short, ushort, or char), their values are converted to the int type, which is also the result type of an operation. When operands are of different integral or floating-point types, their values are converted to the closest containing type, if such a type exists. – Alce Mar 11 '23 at 13:19
  • Instead of adding "SOLVED" you should mark the answer as accepted by clicking the check mark. – Charlieface Mar 12 '23 at 03:23

1 Answers1

1

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators Here is all the informations about the impicit and explicit casting of the operators.

Alce
  • 23
  • 6