C# Language Overflow Ordering matters

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

There is overflow in the following code

int x = int.MaxValue;
Console.WriteLine(x + x + 1L);  //prints -1

Whereas in the following code there is no overflow

int x = int.MaxValue;
Console.WriteLine(x + 1L + x);  //prints 4294967295

This is due to the left-to-right ordering of the operations. In the first code fragment x + x overflows and after that it becomes a long. On the other hand x + 1L becomes long and after that x is added to this value.



Got any C# Language Question?