When must we use checked
operator in C#?
Is it only suitable for exception handling?
Checked operators are used to detect overflow errors that can occur at run time for arithmetic operations that result in too of a large number for the number of bits allocated to the data type of the result in use.
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. Beginning with C# 11, the checked keyword declares an operator specific to a checked context.
According to MSDN, The Checked Keyword in C# is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions. The Unchecked Keyword in C# is used to suppress overflow-checking for integral-type arithmetic operations and conversions.
In a checked context, arithmetic overflow raises an exception. In an unchecked context, arithmetic overflow is ignored and the result is truncated by discarding any high-order bits that don't fit in the destination type.
You would use checked
to guard against a (silent) overflow in an expression.
And use unchecked
when you know a harmless overflow might occur.
You use both at places where you don't want to rely on the default (project-wide) compiler setting.
Both forms are pretty rare, but when doing critical integer arithmetic it is worth thinking about possible overflow.
Also note that they come in two forms:
x = unchecked(x + 1); // ( expression )
unchecked { x = x + 1;} // { statement(s) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With