C# Checked and Unchecked
In C#, the keywords checked and unchecked are used to control whether arithmetic overflow exceptions are thrown or not. The checked keyword ensures that overflow exceptions are thrown, while the unchecked keyword disables this behavior. In this tutorial, we'll discuss how to use checked and unchecked in C#.
Syntax
The syntax for using checked and unchecked in C# is as follows:
// Checked arithmetic
checked {
// code
}
// Unchecked arithmetic
unchecked {
// code
}
The checked and unchecked keywords are used to define a block of code where the behavior of arithmetic overflow is controlled.
Example
Let's say we want to perform an integer addition that produces an arithmetic overflow. Here's how we can use checked and unchecked to handle this situation:
int x = int.MaxValue;
int y = 1;
// Checked arithmetic (throws OverflowException)
checked {
int result = x + y;
Console.WriteLine(result);
}
// Unchecked arithmetic (no exception thrown)
unchecked {
int result = x + y;
Console.WriteLine(result);
}
Output
When we run the example code above, the output will be:
Unhandled exception. System.OverflowException: Arithmetic operation resulted in an overflow.
This is because the integer addition produced an overflow and we used the checked keyword to throw an exception. When we used the unchecked keyword, no exception was thrown.
Explanation
In the example above, we performed an integer addition that produced an arithmetic overflow. We used the checked and unchecked keywords to handle this situation by explicitly defining how arithmetic overflow should be treated.
We used the checked keyword to ensure that an OverflowException was thrown when an arithmetic overflow occurred. When we used the unchecked keyword, no exception was thrown, and the result of the integer addition was wrapped around the maximum value of the integer type.
Use
The checked and unchecked keywords are useful when you want to control how arithmetic overflow is handled in your code. In some situations, you may want to stop execution when an arithmetic overflow occurs, while in others, you may want to allow the overflow to happen.
Important Points
- By default, C# uses the unchecked keyword to disable arithmetic overflow checking.
- The checked and unchecked keywords only affect the behavior of arithmetic operations and not other types of computations.
- You can use the OverflowException class to catch arithmetic overflow exceptions.
Summary
In this tutorial, we discussed how to use checked and unchecked in C# to control how arithmetic overflow is handled. We covered the syntax, example, output, explanation, use, and important points of checked and unchecked in C#. With this knowledge, you can now use checked and unchecked in your C# code to handle arithmetic overflow situations.