David Rutten
David Rutten

Reputation: 4806

Consistent behaviour of the ++ operator in C#

Is the behaviour of the ++ operator as applied to longs in C# consistent when it is applied to long.MaxValue? The call is not made inside a checked block. I need to know if under any circumstances, present or future it could possibly throw an OverflowException instead of wrapping to long.MinValue.

Upvotes: 1

Views: 180

Answers (2)

Jakub Lortz
Jakub Lortz

Reputation: 14894

From C# language specification:

For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the default overflow checking context is unchecked unless external factors (such as compiler switches and execution environment configuration) call for checked evaluation.

Upvotes: 2

sstan
sstan

Reputation: 36523

Even if you're not inside a checked block, if you compile your project with "Check for arithmetic overflow/underflow" in Visual Studio (or use the /checked C# compiler switch), then all your code will behave as if it was inside a checked block by default. So you could absolutely get an overflow exception in that case.

Upvotes: 8

Related Questions