What's up with this, anyway? I do a simple multiplication:
Int64 x = 11111111111; Int64 y = 11111111111; Int64 z = x * y;
And at the end of the multiplication, z shows a value of:
-5670418394979206991
This has clearly overflowed, but no exception is raised. I'd like one to be raised, but...
Note that this is on Windows Phone 7, but I don't think this has any bearing on the issue. Or does it?
You can use a checked block as pointed out already by other answers:
checked { long x = 11111111111; long y = 11111111111; long z = checked(x * y); // ... }
Which results in an exception:
OverflowException: Arithmetic operation resulted in an overflow.
If you are just doing a single operation where you need checking you can use a checked expression instead:
long x = 11111111111; long y = 11111111111; long z = checked(x * y);
You can also set the /checked compiler option to have the default be checked.
To set this compiler option in the Visual Studio development environment:
- Open the project's Property Pages dialog box. For details, see Setting Visual C# Project Properties.
- Click the Configuration Properties folder.
- Click the Build property page.
- Modify the Check for Arithmetic Overflow/Underflow property.
If you change the default to checked you can use unchecked blocks or expressions to get the unchecked behaviour again.
Check it:
checked { Int64 x = 11111111111; Int64 y = 11111111111; Int64 z = x * y; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With