An unchecked operator, in C#, is an operator used to disable overflow checking during the evaluation of expressions and conversions.
While performing integral-type arithmetic operations using expressions containing numeric data types, it can result in an overflow exception if the result of the operation is too large to be represented in the number that is allocated with a specific number of bits based on its type. In cases where an overflow is an acceptable result of operation, it is necessary to suppress the exception and continue with the program. An unchecked operator is used in such scenarios by setting an unchecked context in which the arithmetic overflow is ignored with the truncation of the result.
In contrast to C/C++, which ignores the possibility of overflow, C# provides the feature to either handle or ignore overflow by providing checked and unchecked operators. The unchecked operator is often used in the section of a project that is compiled in checked context. Some of the algorithms where the unchecked operator can be used include checksums, encryption logic and random number generation.
An unchecked operator is used with the keyword "unchecked" on an expression and as a statement in a block of code. It sets an execution context in which the most significant bits of the result are discarded on the occurrence of an integer overflow, while execution is continued. The context of unchecked is applicable to the statements enclosed within the "unchecked" statement and not to nested function calls.
For example, when the product of two large integers of data type requires the use of short for some purpose without any necessity for checking for the occurrence of an overflow, an unchecked operator can be used.
In general, an expression that contains constant terms can only be checked for an overflow during compile time. An unchecked operator can be used to avoid checking for overflow in such expressions and also for expressions that contain non-constant terms that are unchecked by default, both at run time and compile time.
An unchecked operator cannot be overloaded.
Because the use of an unchecked operator has a performance penalty, it should only be used where the overflow does not cause any issues.
Read More »