Enumerable.Sum
is implemented with calculating sum with checked
keyword.
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
It is using the following code- Source Reference - Microsoft:
public static int Sum(this IEnumerable<int> source) {
if (source == null) throw Error.ArgumentNull("source");
int sum = 0;
checked {
foreach (int v in source) sum += v;
}
return sum;
}
If you do the same with:
checked
{
int temp = 2147483647;
Console.WriteLine(temp + 1); //returns -2147483648
}
You will get the same exception