The checked
keyword is used to explicitly enable arithmetic overflow checking for numeric expressions. By default, C# performs unchecked arithmetic, which means it does not throw exceptions when an overflow occurs during arithmetic operations on numeric data types. However, when the checked
keyword is used, the runtime checks for arithmetic overflow, and if it detects an overflow, it throws an OverflowException
.
Here's how you can use the checked
keyword:
int a = int.MaxValue;
int b = 1;
// Without 'checked' keyword, overflow occurs but does not throw an exception.
int result1 = a + b;
Console.WriteLine(result1); // Output: -2147483648 (integer overflow)
// With 'checked' keyword, an exception is thrown for overflow.
try
{
checked
{
int result2 = a + b;
Console.WriteLine(result2); // This line will not be executed due to exception.
}
}
catch (OverflowException ex)
{
Console.WriteLine("Arithmetic overflow occurred: " + ex.Message);
}
In this example, we try to add int.MaxValue
(the maximum value an int
can hold) to 1
. Without the checked
keyword, the overflow occurs, and the result wraps around, producing -2147483648
. However, when the checked
keyword is used, the addition throws an OverflowException
since the result exceeds the maximum value an int
can represent.
By default, C# uses unchecked arithmetic to improve performance because overflow checking incurs some overhead. However, for cases where you need to ensure data integrity and detect overflow conditions, you can use the checked
keyword to enable arithmetic overflow checking within specific code blocks.