Unchecked context and overflow

  • Thread starter Thread starter BMermuys
  • Start date Start date
B

BMermuys

Hi,
inline

Patrick Kristiansen said:
Hello!

I think I misunderstood something here. If for example I have a byte,
and I know it's going to overflow, how do I make sure, that the
compiler doesn't give me an error? I've done this in an unchecked
context, so shouldn't ignore an, for example, obvious overflow.

For example:
void Method()
{
unchecked
{
byte val = 255 + 1;

256 is an integer and there's no implicit cast to a byte, so you get an
error.

You can explicitly cast the int to byte, which will cause the overflow and
so it must be inside an unchecked block

unchecked
{
byte val = (byte)(255+1);
....
};

HTH,
greetings
 
Hello!

I think I misunderstood something here. If for example I have a byte,
and I know it's going to overflow, how do I make sure, that the
compiler doesn't give me an error? I've done this in an unchecked
context, so shouldn't ignore an, for example, obvious overflow.

For example:
void Method()
{
unchecked
{
byte val = 255 + 1;
Console.WriteLine(byte);
}
}

Thanks in advance,
Patrick
 
Back
Top