Checked context in C# and F#

C#

By default, arithmetic operations and conversions in C# execute in an unchecked context, you can use the checked keyword to switch a block of code to the checked context so that any arithmetic overflow that occurs in that block of code will cause the OverflowException to be thrown:

image

However, the scope of the checked context is local to the method – i.e. if in your checked block you call another method then that method is not part of your scope and can cause arithmetic overflow without throwing any exceptions:

image

This might seem strange at first, but the reason for it is that whether or not an exception should be thrown for an arithmetic overflow/underflow is baked into the MSIL code the compiler generates rather than a runtime decision. When the OverflowInt method above is compiled, it’s compiled to NOT throw any exceptions when an overflow occurs, therefore regardless of where the method is called from no OverflowException will be thrown from inside the OverflowInt method.

However, it is possible to change the default behaviour for a given project by making a simple change to a project setting. Right-click on a project (inside VS) and go into project properties, find the Build tab, and click “Advanced…”. In the subsequent pop-up dialog there’s a ‘Check for arithmetic overflow/underflow’ checkbox:

image

F#

F# uses a different approach, it uses operator shadowing so that whenever you open the Checked module it overloads the standard arithmetic operators to include checks for arithmetic overflow/underflow and throws the OverflowException:

 image

Suppose if you have the following module, the function f will not throw exceptions for arithmetic overflows because at the point it is defined the arithmetic operators have not been overloaded yet:

image

Subsequently, if you have code that uses this module, the overloaded operators from the Checked module will not apply here just because you’ve opened an module that imports the Checked module:

image

It is possible to simulate the behaviour of the C# checked keyword as Tomas Patricek suggested here, although his solution only works for the int type but nonetheless it gives you a good idea of how one might be able to do so:

image