Sunday, April 27, 2008

C# checked and unchecked keywords.

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);



outputChecked1



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);


outputChecked2



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);
}



outputChecked3



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);


outputChecked4



 



Reference:



checked (C# Reference)



unchecked (C# Reference)



Checked and Unchecked

No comments: