Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When must we use checked operator in C#?

When must we use checked operator in C#?
Is it only suitable for exception handling?

like image 314
masoud ramezani Avatar asked Mar 02 '10 14:03

masoud ramezani


People also ask

What is the use of checked operator?

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.

What is the purpose of checked block in C sharp?

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.

What is the use of checked and unchecked keyword?

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.

What is meant by checked and unchecked blocks?

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.


1 Answers

You would use checkedto 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) }
like image 111
Henk Holterman Avatar answered Oct 08 '22 04:10

Henk Holterman