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?

5
  • 1
    b3 is an int (max value 2 147 483 647), b1 is a byte (max value 255) Commented Nov 10, 2021 at 12:05
  • 1
    Another relevant info: stackoverflow.com/q/9457655/5311735 Commented Nov 10, 2021 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. Commented Nov 10, 2021 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. Commented Nov 10, 2021 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. Commented Nov 10, 2021 at 12:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.