C# Language Overflow during operation


Example

Overflow also happens during the operation. In the following example, x is an int, 1 is an int by default. Therefore addition is an int addition. And the result will be an int. And it will overflow.

int x = int.MaxValue;               //MaxValue is 2147483647
long y = x + 1;                     //It will be overflown
Console.WriteLine(y);               //Will print -2147483648
Console.WriteLine(int.MinValue);    //Same as Min value

You can prevent that by using 1L. Now 1 will be a long and addition will be a long addition

int x = int.MaxValue;               //MaxValue is 2147483647
long y = x + 1L;                    //It will be OK
Console.WriteLine(y);               //Will print 2147483648