Raghunath Majhi
Raghunath Majhi

Reputation: 41

Byte Overflow Concept in C#

I have started learning C# and need to clear some of confusion on overflown concept. As we aware of that if we exceed the limit of any data type , C# simply returns 0 .

eg : byte b = 255; if we increase the value of b by 1, then the value of b will be zero.for below code i am getting output as 256.

 using System;
 namespace HelloWorld{
     class program{
          static void Main(){
                  byte b = 255;
                  Console.WriteLine(b+1);
           }
       }
  }

Instead of 0, i am getting output as 256 , which is out of the limit of b of type byte. How is this possible ?.

using System;
namespace HelloWorld{
class program{
    static void Main(){
        byte b = 255;
        b = b+1
        Console.WriteLine(b);
    }
}

for above code i am getting compilation error I.e error CS0266: Cannot implicitly convert type int' tobyte'. An explicit conversion exists (are you missing a cast?)

Help !!!!

Upvotes: 3

Views: 1676

Answers (3)

tmaj
tmaj

Reputation: 34967

The (clue to the) answer to your queries about the compilation error and 256 is in the output of the following snippet:

byte b = 255;
Console.WriteLine($"{b + 1}, {(b+1).GetType()}");
Console.ReadLine();

Output:

256, System.Int32 <-- not `byte`

As for wrapping, I think the following snippet illustrates the concept quite well.

for (int i = 250; i < 260; i++)
{
     byte b = (byte)i;
       Console.WriteLine($"{i} => {b,3} ({Convert.ToString(b, 2).PadLeft(8, '0')})");
}

Output:

250 => 250 (11111010)
251 => 251 (11111011)
252 => 252 (11111100)
253 => 253 (11111101)
254 => 254 (11111110)
255 => 255 (11111111)
256 =>   0 (00000000)
257 =>   1 (00000001)
258 =>   2 (00000010)
259 =>   3 (00000011)

Upvotes: 8

esskar
esskar

Reputation: 10940

It is a little bit different here. In your first example, the expression b+1 gets converted to an integer, as 1 by it self is always an integer, that's why your output is 256.

In the second example, you are trying to at an integer to an byte again, which is converted again to an integer, and then you want to assign the result back to an byte, which is not possible without a cast.

So, in c#, when adding numbers, the result is automatically converted to the type that can hold the larger value.

Same goes for double or float.

float f = 0.1;
double d = 0.1;
var x = f + d; // x is a double

To avoid the automatic conversion, you need to cast like b + (byte)1

To avoid the automatic conversion, you need to cast like (byte)(b + 1) (thanks @fubo)

Upvotes: 0

Safwan Shaikh
Safwan Shaikh

Reputation: 546

byte b = 255;
b = b + 1;

This throws an error because b is of type byte and it takes 1 as int literal. You need to do type casting here.

 byte b = 255;
 b++;
 Console.WriteLine(b);

This will gives you 0.

Upvotes: 1

Related Questions