Integral arithmetic overflow check operators - CSharp Language Basics

CSharp examples for Language Basics:Operator

Introduction

The checked operator tells the runtime to generate an OverflowException rather than overflowing silently.

The checked operator affects expressions with the ++, --, +, - (binary and unary), *, /, 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;
   ...
}

Using unchecked operator

int x = int.MaxValue;
int y = unchecked (x + 1);
unchecked { int z = x + 1; }

Related Tutorials