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.