What is the use of checked and unchecked keyword ?

In C# by default there is no overflow checking(except const variables) while performing arithmetic operations and conversions on integral values. To control the overflow conditions checked and unchecked keywords are come to the picture.

Checked :-

It ensure that only max value can be assigned to the LHS variable. If we will try to push value more then its max value then it will throw an exception.


class Program

{

public short a = 30000;

public short b = 20000;

public short c;

 

public int Add()

{

try

{

c = checked((short)(a + b));

 

}

catch (System.OverflowException e)

{

System.Console.WriteLine(e.ToString());

}

return c;

}

unchecked keyword is used to by pass the default behavior of overflow checking for const variable. Constant variables are checked for overflow at compile time.