0

Could anyone explain it to me that how output of Console.WriteLine(a); equals to 44 in this code block.

byte a = 200;
byte b = 100;
var c = a + b;
Console.WriteLine(c.GetType());  // output: System.Int32
Console.WriteLine(c);  // output: 300

a += b;
Console.WriteLine(a.GetType());
Console.WriteLine(a);  // output: 44
Console.ReadLine();
Steph
  • 831
  • 6
  • 19
i.1.618
  • 7
  • 3
  • Perhaps we could be more helpful if you can tell us what you expected it to output. – Sweeper Jun 17 '20 at 11:50
  • 2
    That code doesn't compile... `**a` is not legal c# syntax. Also, it seems there are a lot of irrelevant lines of code there? – Rufus L Jun 17 '20 at 11:52
  • 6
    200 + 100 = 300 which exceeds the maximum value a `byte` can hold and ends up as 300 - 256 = 44, per modular arithmetic. – Jeroen Mostert Jun 17 '20 at 11:53
  • 1
    The result of `byte+byte` is - against what you might expect - `int`, so: it can't overflow; but `byte += byte` retains the `byte`-ness, so: overflows – Marc Gravell Jun 17 '20 at 11:54
  • Others have answered your question, but if you want your numbers to add up, then you need a larger type, like `int`, or `long` which hold much larger numbers. – Neil Jun 17 '20 at 11:54

1 Answers1

4

This line:

a += b;

Is equivalent to this line:

a = (byte) (a + b);

... except that a is only evaluated once. The result of a + b is of type int (with a value of 300 in this case), and the cast to byte truncates that to 8 bits (the size of the byte type), leaving a result of 44.

From section 12.18.3 of the ECMA C# 5 standard:

An operation of the form x op= y is processed by applying binary operator overload resolution (§12.4.5) as if the operation was written x op y. Then,

  • If the return type of the selected operator is implicitly convertible to the type of x, the operation is evaluated as x = x op y, except that x is evaluated only once.
  • Otherwise, if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once.
  • Otherwise, the compound assignment is invalid, and a binding-time error occurs.
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @Neil: If they want to only read the first part, that doesn't include the spec, they can do so - I think the first part is fairly easy to understand. I've added a tiny bit more explanation, but I think it's already pretty reasonable. You can add your own answer to explain it differently of course. – Jon Skeet Jun 17 '20 at 12:01