Assuming default arithmetic overflow (not)checking, the following code
Action<Int32[]> action;
checked
{
action = array =>
Console.WriteLine(array[0] + array[1]);
}
var items = new[]
{
Int32.MaxValue,
Int32.MaxValue
};
action(items);
will result in
System.OverflowException: Arithmetic operation resulted in an overflow..
If we set project settings to /checked, and replace checked {
with unchecked {
, the exception won't be thrown.
So, can we rely on this behavior, or is it safer to array => unchecked (array[0] + array[1])
?
In the last officially published C# spec, it says the following:
8.11 (...) The checked statement causes all expressions in the block to be evaluated in a checked context, and the unchecked statement causes all expressions in the block to be evaluated in an unchecked context. (...)
I'd say pretty confidently that action
will always be evaluated in a checked/ unchecked context which is the current behavior you are seeing and I wouldn't expect this to change in the future.
To expand a little more on my answer, if you check the compiled code, you'll see that Console.WriteLine(array[0] + array[1])
inside the checked
statement is actually compiled as the equivalent of Console.WriteLine(checked (array[0] + array[1]))
so there is really no need to do it yourself, the compiler will do it anyways.