-4

When i try the following :

const int x = 1000;
byte b1 = (byte)x;

//Or

byte b2 = (byte)1000;

The compiler claims that it didn't convert constant 1000 to b1 or b2.

But when i tried the following :

const int x = 1000;
byte b1 = unchecked((byte)x);

//Or

byte b2 = unchecked((byte)1000);

This code worked fine.Why?

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Brahim Boulkriat
  • 984
  • 2
  • 9
  • 21

2 Answers2

3

The compiler claims that it didn't convert constant 1000 to b1 or b2.

Yes because In .NET Framework, byte represents 8-bit unsigned integer and it can hold the values from 0 to 255.

But when i tried the following... This code worked fine.Why?

When you use unchecked keyword, you are allowing the overflow is not flagged.

If the unchecked environment is removed, a compilation error occurs. The overflow can be detected at compile time because all the terms of the expression are constants.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
3

It is obvious.

byte has range 0-255. You are trying to put there 1000 which leads to overflow. unchecked allows it because

The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93