Checked and unchecked keywords used to control the overflow checking context for integer data type arithmetic operations and conversion.
int z= int.MaxValue + 10;
above statement will not give any error. If you want that above code should throw an error in case of overflow than you have to use checked keyword.
try
{
checked
{
int x = int.MaxValue;
int x = int.MaxValue;
int z= x + 10;
}
}
catch(Exception ex)
{
Console.WriteLine("Overflow");
}
the above code will give error of Overflow.
unchecked behave same as if you are not using checked keyword.
In case of const variable it gives overflow error at compile time.
Ex
const int x = int.MaxValue;
const int y = int.MaxValue;
int z= x + y;
above statement will give compile time error of overflow in this condition if you want to bypass this error than use unchecked keyword.
int z = unchecked (x + y);
the above statement will not give any error.
In case of const variable it gives overflow error at compile time.
Ex
const int x = int.MaxValue;
const int y = int.MaxValue;
int z= x + y;
above statement will give compile time error of overflow in this condition if you want to bypass this error than use unchecked keyword.
int z = unchecked (x + y);
the above statement will not give any error.
No comments:
Post a Comment