Unchecked context and overflow

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
 
P

Patrick Kristiansen

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top