Checked and unchecked keyword in C# full Explanation
In C#, the `checked` and `unchecked` keywords are
used to control the behavior of overflow checking during arithmetic operations.
Here's a full explanation of the `checked` and `unchecked` keywords:
1.
checked Keyword:
v The
`checked` keyword enables overflow checking for arithmetic operations.
v When
overflow checking is enabled, if an arithmetic operation exceeds the range or
capacity of the data type, it throws a `System.OverflowException`.
v By
default, overflow checking is disabled in C#.
v Example:
checked
{
int x = int.MaxValue;
int y = 1;
int result = x + y; // Throws OverflowException
}
2.
unchecked Keyword:
v The
`unchecked` keyword disables overflow checking for arithmetic operations.
v When
overflow checking is disabled, if an arithmetic operation exceeds the range or
capacity of the data type, the result is silently truncated or wrapped around.
v This
can lead to unexpected or incorrect results if the data type is unable to hold
the resulting value.
v Example:
unchecked
{
int x = int.MaxValue;
int y = 1;
int result = x + y; // Result wraps around to int.MinValue
}
3.
Default Behavior:
v By
default, without explicitly using either `checked` or `unchecked`, C# follows
the rules of unchecked arithmetic operations.
v This
means that overflow checking is disabled, and the result of an arithmetic
operation that exceeds the range or capacity of the data type is silently
truncated or wrapped around.
v Example:
int x = int.MaxValue;
int y = 1;
int result = x + y; // Result wraps around to int.MinValue
4.
Controlling Overflow Checking:
v You
can explicitly enable or disable overflow checking using the `checked` and
`unchecked` keywords respectively.
v You
can apply these keywords to a block of code, an individual statement, or a
specific expression.
v Example:
checked
{
// Overflow checking enabled for this
block
int x = int.MaxValue;
int y = 1;
int result = x + y; // Throws OverflowException
}
unchecked
{
// Overflow checking disabled for this
block
int x = int.MaxValue;
int y = 1;
int result = x + y; // Result wraps around to int.MinValue
}
The `checked` and `unchecked` keywords provide control
over how overflow during arithmetic operations is handled in C#. They allow you
to choose whether to throw an exception (`checked`) or wrap/truncate the result
silently (`unchecked`) when an arithmetic operation exceeds the range or
capacity of the data type.
0 Comments