C# arithmetic statements can be executed in **checked** or **unchecked** context. "Checked" context checks overflow and raises exception when a arithmetic overflow is detected.

Sample:

short x;

short y;

short z;

x = 10;

y = 20;

z = (short) (x + y);

Debug.Print("\nz = {0}, where x = {1}, y = {2} and z = (short) (x + y);\n", z, x, y);

x = short.MaxValue;

y = short.MaxValue;

z = (short) (x + y);

Debug.Print("z = {0}, where x = {1}, y = {2} and z = (short) (x + y);\n", z, x, y);

x = short.MaxValue;

y = short.MaxValue;

try

{

z = checked((short) (x + y));

Debug.Print("z = {0}, where x = {1}, y = {2}\n", z, x, y);

} catch (OverflowException)

{

Debug.Print("OverflowException ==> where x = {1}, y = {2} and z = checked((short) (x + y));\n", z, x, y);

}

x = short.MaxValue;

y = short.MaxValue;

z = unchecked((short)(x + y));

Debug.Print("z = {0}, where x = {1}, y = {2} and z = unchecked((short)(x + y));\n", z, x, y);

Reference:

## No comments:

Post a Comment