Check Operator in C#

Check operator tells the runtime to generate an OverflowException rather than overflowing silently when an integral expression or statement exceeds the arithmetic limits of that type.
The checked operator affects expressions with the ++,–,+,-,*,/ and explicit conversion operators between integral types. Checked can be used around either an expression or a statement block.

For example:
int a = 1000000;
int b = 1000000;
int c = checked(a*b); //Checks just the expression.
checked //Checks all expressions in statement block.

c = a * b;

If we are using a compiler with the /checked command line then this will check all the expressions in the program.
In such a case if we need to disable overflow checking just for specific expressions or statements, we can do so with the unchecked operator.

For example:
int x = int.MaxValue;
int y = unchecked (x + 1); //Leaves the expression from checking.
unchecked //Leaves all the expressions inside the block from checking.
int z = x + 1;
Against all the above statements let’s say we have a constant expression then the overflow will be evaluated at the compile time itself unless we are applying the unchecked operator.
int x = int.MaxValue + 1; //Compile time error.
int y = unchecked (int.MaxValue + 1); //No errors.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s