Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is the checked and unchecked keyword.
From MSDN:
If you don’t want overflow to happen, you can start using the checked keyword:
So use
The default is
From MSDN:
C# statements can execute in either checked or unchecked context. In a checked context, arithmetic overflow raises an exception. In an unchecked context, arithmetic overflow is ignored and the result is truncated.
If neither checked nor unchecked is specified, the default context depends on external factors such as compiler options.
An example, by default if you go above the MaxValue of an integer, the runtime will start again from the MinValue allowing you to do an overflow. This is the equivalent of the unchecked mode:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int i = int.MaxValue -50; | |
unchecked { | |
i+= 100; //Will just work | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int i = int.MaxValue -50; | |
checked { | |
i+= 100; // OverflowException: "Arithmetic operation resulted in an overflow." | |
} |
So use
checked
when you don't want accidental overflow / wrap-around to be a problem, and would rather see an exception. unchecked
explicitly sets the mode to allow overflow The default is
unchecked
unless you tell the compiler otherwise(through code or a compiler switch /checked
).