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:
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:
If you don’t want overflow to happen, you can start using the checked keyword:
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
).