Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable checking of overflow with Array.Sum

Tags:

c#

linq

overflow

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

like image 703
Jared Avatar asked Jan 04 '12 07:01

Jared


1 Answers

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.

like image 171
Jeff Mercado Avatar answered Sep 25 '22 13:09

Jeff Mercado