There is a Pex4Fun problem that asks the user to write code that finds the sum of an array.
using System;
using System.Linq;
public class Program {
public static int Puzzle(int[] a) {
return a.Sum();
}
}
Pex expects that it can pass {-1840512878, -2147418112} and get back the underflowed number, 307036306, however the LINQ method, Array.Sum(), checks for overflow.
I can't use the unchecked keyword around the method invocation of a.Sum() because the addition happens inside of the method.
Is there any way to disable the checking of underflow/overflow with Array.Sum()?
The specification for all of the Enumerable.Sum()
overloads will throw an OverflowException
if there is an overflow. This is not configurable, this is by design. Just don't use that method.
You can still use LINQ here and use the Enumerable.Aggregate()
method instead and not do the checking:
public static int Puzzle(int[] a)
{
return a.Aggregate((sum, i) => unchecked(sum + i));
}
Otherwise do it by hand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With