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:
I'd say pretty confidently that
actionwill 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 thecheckedstatement is actually compiled as the equivalent ofConsole.WriteLine(checked (array[0] + array[1]))so there is really no need to do it yourself, the compiler will do it anyways.