By default, C # does not check overflow when processing numbers. This includes things like wrapping from int.MaxValue to int.MinValue in addition and multiplying, as well as when long pressed on int s. To control this, use the checked and unchecked keywords or the /checked option for the compiler.
The value 1942903641 is the result when your long truncated to int . It comes from the 32 least significant bits of the long value, taken as two additions , indicated by an integer.
When using foreach it is important to know that if you declare a type that does not match an enumerated type, it will process it as if you were using that type. foreach (int i in myCollection) compiles into something like int i = (int)myEnumerator.Current; , not int i = myEnumerator.Current; . You can use foreach (var i in myCollection) to avoid such errors in the future. var recommended for use with loop variables in for and foreach expressions.
You can see the results of various things in the following example (hexadecimal output is used to display truncation more clearly: they have the same final digits, int just lacks some more significant digits):
checked { Int64 a = 12345678912345; Console.WriteLine(a.ToString("X")); Console.WriteLine((a % ((long)uint.MaxValue + 1L)).ToString("X")); try { Console.WriteLine(((int)a).ToString("X"));
It is output:
B3A73CE5B59 73CE5B59 It threw! Arithmetic operation resulted in an overflow. B3A73CE5B59 73CE5B59 73CE5B59
source share