Enumerable.Sumimplemented with the calculation of the amount with the keyword checked.
checked (C # link)
The checked keyword is used to explicitly enable overflow checking for integral types of arithmetic operations and transformations.
The following code is used: Source link - 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:
checked
{
int temp = 2147483647;
Console.WriteLine(temp + 1);
}
You will get the same exception
Habib source
share