Overflow exception is throwing even the value exceeds the limit

Why the following code Gives output as -2 instead for throwing overflow exception?

 long x = long.MaxValue;
 long y = long.MaxValue + x;
Jon Skeet
people
quotationmark

Presumably because you're executing it in an unchecked context. Arithmetic on the primitive integer types can execute in a checked or unchecked context. Operations which overflow throw an exception in a checked context, and just use the bottom N bits (depending on the type) in an unchecked context. The default depends on the project settings, but the "default default" is unchecked.

You can either explicitly perform the operation in a checked context, or change the project settings.

Doing it explicitly (just for the arithmetic):

long x = long.MaxValue;
long y = checked(long.MaxValue + x);

Note that constant expressions are checked at compile time, and overflow will result in a compile-time error unless it's explicitly unchecked (regardless of project settings). For example:

long x = long.MaxValue + 1; // Error
long y = unchecked(long.MaxValue + 1); // Equivalent to y = long.MinValue

people

See more on this question at Stackoverflow