I’ve ended the previous post on numeric conversions talking about overflow and how it might surprise you from time to time. For instance, here’s an example that might get you off guard:
Running the previous snippet ends up printing the following:
4294967295 – -1
Now, even though this might be ok in several scenarios, there might some times when you want to get an exception if the value is “too big” for the variable. In these cases, you can resort to the checked keyword, which can be applied to a statement or expression, making it run in a checked context:
In the previous snippet, the cast from the uint value into a int is perfomed in a checked context. Since the uint number is way “too big” to be stored in an int, we’ll end up getting a OverflowException. Besides casts, you can also use the checked keyword when performing arithmetic operations. Notice also that the checked keyword can be used to run an entire block of code in the checked context:
In fact, and if that is your desire, you can also configure the C# compiler so that everything is run into a checked context by default. You can do this by passing the /checked flag from the command line or by going to the VS build tab on the project’s options windows and setting the “Check for arithmetic overflow/underflow checkbox” on the dialog that is shown when you hit the advanced button.
In practice, you probably shouldn’t use checked contexts in all your arithmetic operations because checking contexts can make them really slow. If this is negligible or not, it will depend on the operations performed by your program. However, you should keep in mind that it might have some negative impacts in the performance of your app. Bottom line, if you decide to go crazy and run everything in the checked context, don’t forget to measure the impacts in the performance of the app.
And that’s it for now. Stay tuned for more.