Checked context in C# and F#

C#

By default, arith­metic oper­a­tions and con­ver­sions in C# exe­cute in an unchecked con­text, you can use the checked key­word to switch a block of code to the checked con­text so that any arith­metic over­flow that occurs in that block of code will cause the Over­flowEx­cep­tion to be thrown:

image

How­ev­er, the scope of the checked con­text is local to the method – i.e. if in your checked block you call anoth­er method then that method is not part of your scope and can cause arith­metic over­flow with­out throw­ing any excep­tions:

image

This might seem strange at first, but the rea­son for it is that whether or not an excep­tion should be thrown for an arith­metic overflow/underflow is baked into the MSIL code the com­pil­er gen­er­ates rather than a run­time deci­sion. When the Over­flowInt method above is com­piled, it’s com­piled to NOT throw any excep­tions when an over­flow occurs, there­fore regard­less of where the method is called from no Over­flowEx­cep­tion will be thrown from inside the Over­flowInt method.

How­ev­er, it is pos­si­ble to change the default behav­iour for a giv­en project by mak­ing a sim­ple change to a project set­ting. Right-click on a project (inside VS) and go into project prop­er­ties, find the Build tab, and click “Advanced…”. In the sub­se­quent pop-up dia­log there’s a ‘Check for arith­metic overflow/underflow’ check­box:

image

F#

F# uses a dif­fer­ent approach, it uses oper­a­tor shad­ow­ing so that when­ev­er you open the Checked mod­ule it over­loads the stan­dard arith­metic oper­a­tors to include checks for arith­metic overflow/underflow and throws the Over­flowEx­cep­tion:

 image

Sup­pose if you have the fol­low­ing mod­ule, the func­tion f will not throw excep­tions for arith­metic over­flows because at the point it is defined the arith­metic oper­a­tors have not been over­loaded yet:

image

Sub­se­quent­ly, if you have code that uses this mod­ule, the over­loaded oper­a­tors from the Checked mod­ule will not apply here just because you’ve opened an mod­ule that imports the Checked mod­ule:

image

It is pos­si­ble to sim­u­late the behav­iour of the C# checked key­word as Tomas Patricek sug­gest­ed here, although his solu­tion only works for the int type but nonethe­less it gives you a good idea of how one might be able to do so:

image