Disable overflow checking with Array.Sum

There is a Pex4Fun problem that asks the user to write code that finds the sum of the array.

using System; using System.Linq; public class Program { public static int Puzzle(int[] a) { return a.Sum(); } } 

Pex expects it to be able to pass {-1840512878, -2147418112} and return an invalid number 307036306, however the LINQ method, Array.Sum (), checks for overflow.

I can’t use the unverified keyword around the a.Sum () method call, because adding happens inside the method.

Is there a way to disable underflow / overflow checking with Array.Sum ()?

+4
source share
1 answer

The specification for all Enumerable.Sum() overloads will raise an OverflowException if there is an overflow. It is not customizable, it is by design. Just do not use this method.

You can use LINQ here and use Enumerable.Aggregate() instead and not check:

 public static int Puzzle(int[] a) { return a.Aggregate((sum, i) => unchecked(sum + i)); } 

Otherwise, do it manually.

+12
source

Source: https://habr.com/ru/post/1389215/


All Articles