Handling integer overflow is a common task, but what’s the best way to handle it in C#? Is there some syntactic sugar to make it simpler than with other languages? Or is this really the best way?
int x = foo();
int test = x * common;
if(test / common != x)
Console.WriteLine("oh noes!");
else
Console.WriteLine("safe!");
I haven’t needed to use this often, but you can use the checked keyword:
Will result in a runtime exception if overflows. From MSDN:
I should also point out that there is another C# keyword,
unchecked, which of course does the opposite ofcheckedand ignores overflows. You might wonder when you’d ever useuncheckedsince it appears to be the default behavior. Well, there is a C# compiler option that defines how expressions outside ofcheckedanduncheckedare handled: /checked. You can set it under the advanced build settings of your project.If you have a lot of expressions that need to be checked, the simplest thing to do would actually be to set the
/checkedbuild option. Then any expression that overflows, unless wrapped inunchecked, would result in a runtime exception.