Search code examples
c#arrayssumintoverflow

Array.Sum() results in an overflow


I have an int array like this

int[] arr = {256741038,623958417,467905213,714532089,938071625};

and then I created an int64 var

Int64 sum = arr.Sum();

But this reslted in an overflow

Run-time exception (line 19): Arithmetic operation resulted in an overflow.

How can I solve this problem without using loop to sum it up ? (array type must be int)


Solution

  • The issue is that while the individual values fit within an int, the sum of these numbers results is larger than an int can hold.

    You therefore need to cast the values to long (or another datatype that takes numbers that big, but since you're using Int64...):

    long sum = arr.Sum(v => (long)v);