One problem with the for loop solutions above is that for the following input array with all positive values, the sum result is negative:
int[] arr = new int[] { Int32.MaxValue, 1 };
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
Console.WriteLine(sum);
The sum is -2147483648, as the positive result is too big for the int data type and overflows into a negative value.
For the same input array the arr.Sum() suggestions cause an overflow exception to be thrown.
A more robust solution is to use a larger data type, such as a "long" in this case, for the "sum" as follows:
int[] arr = new int[] { Int32.MaxValue, 1 };
long sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
The same improvement works for summation of other integer data types, such as short, and sbyte. For arrays of unsigned integer data types such as uint, ushort and byte, using an unsigned long (ulong) for the sum avoids the overflow exception.
The for loop solution is also many times faster than Linq .Sum()
To run even faster, HPCsharp nuget package implements all of these .Sum() versions as well as SIMD/SSE versions and multi-core parallel ones, for many times faster performance.