6

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()?

1

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't unchecked the default?
Yes, but defaults can be overridden.
@Baruch Yes, the operation itself is unchecked by default, but in this case, the addition is explicitly made checked so we have to work around that. I'm just making it explicitly clear that this is intended to be unchecked. Someone might look at this and get the big-brained idea to switch to Sum() not knowing that it's checked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.