Difference
between Checked and Unchecked keywords in .NET
-
S.No Checked keywordUnchecked keyword1The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.i.e., Checked Key word is used to enforce the compiler to check the buffer overflow while operating arithmetic operators.The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.i.e.,Unchecked Keyword is used to enforce the compiler to do not check that is there any buffer overflow or Not.2 If there is any Buffer overflow code will throw exception.If here any Buffer overflow is occurred it will just truncate the value but not throw exception
Example
for Checked keyword:
static
void Main(string[] args)
{
int
_value1 = 1500056564;
int
_value2 = 1200046565;
checked
{
//
this Code will give exception BuferOverflow
System.Console.WriteLine(_value1
* _value2); System.Console.Read();
}
}
Example
for Unchecked keyword:
static
void Main(string[] args)
{
int
_value1 = 1500056564;
int
_value2 = 1200046565;
unchecked
{
//
This Code will Not Give Exception
System.Console.WriteLine(_value1
* _value2);
System.Console.Read();
}
}
Note:
Both the Checked and Unchecked keywords control whether or not an
exception will be thrown when an operation causes a number to
overflow.
No comments:
Post a Comment