0

Can someone explain the outputs of below code?

using System;
                    
public class Program
{
    public static void Main()
    {
        byte b1 = 190;
        byte b2 = 66;
        var b3 = b1 + b2;
        Console.WriteLine(b3);
        b1 += b2;
        Console.WriteLine(b1);
    }
}

Output

256
0

Why does first additions gives 256, but the second one gives 0?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Yogesh
  • 1,565
  • 1
  • 19
  • 46
  • 1
    b3 is an int (max value 2 147 483 647), b1 is a byte (max value 255) – SomeBody Nov 10 '21 at 12:05
  • 1
    Another relevant info: https://stackoverflow.com/q/9457655/5311735 – Evk Nov 10 '21 at 12:07
  • I see no strange outputs. Also, read the docs and search: Byte.MaxValue is 255, then a rollover occurs. Don't know who upvoted, but this is not a unique, well-researched question. – CodeCaster Nov 10 '21 at 12:08
  • @CodeCaster I think it's somewhat confusing that `b1 = b1 + b2` will not compile, but `b1 += b2` will silently cast int to byte. – Evk Nov 10 '21 at 12:29
  • @Evk if they tried that, they'd have had a compiler error to start their search with and to mention in their question. – CodeCaster Nov 10 '21 at 12:30

0 Answers0