Shouldn’t this cause an Overflow? It doesn’t!

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:

  1. Open the project’s Property Pages dialog box. For details, see Setting Visual C# Project Properties.
  2. Click the Configuration Properties folder.
  3. Click the Build property page.
  4. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)