Pregunta

What could be the reason for the different behaviour of this:

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

List<int> ltemp = new List<int>() { 2147483647, 1 };
Console.WriteLine(ltemp.Sum()); //returns OverFlowException
¿Fue útil?

Solución

Enumerable.Sum is implemented with calculating sum with checked keyword.

checked (C# Reference)

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top