Different LINQ-Sum behavior and manual addition of integer values

What could be the reason for this behavior:

int temp = 2147483647;
Console.WriteLine(temp + 1); //returns -2147483648 

List<int> ltemp = new List<int>() { 2147483647, 1 };
Console.WriteLine(ltemp.Sum()); //returns OverFlowException
+4
source share
1 answer

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); //returns -2147483648
}

You will get the same exception

+6
source

Source: https://habr.com/ru/post/1536801/


All Articles