Checked and Unchecked Keywords in C#: What They Do and When to Use
checked keyword forces the runtime to throw an exception if an arithmetic overflow occurs, while the unchecked keyword allows overflow without error, wrapping the value silently. These keywords help control how your program handles numbers that go beyond their limits.How It Works
Imagine you have a small box that can only hold numbers up to a certain size. If you try to put a bigger number in it, the box either tells you there's a problem or just wraps around and starts over from the smallest number. In C#, checked is like the box that warns you by throwing an error when the number is too big, while unchecked quietly wraps the number around without any warning.
By default, arithmetic operations in C# may or may not check for overflow depending on compiler settings. Using checked ensures that if a calculation goes beyond the allowed range of the data type, the program will throw an OverflowException. Using unchecked tells the program to ignore overflow and continue, which can be faster but riskier.
Example
This example shows how checked throws an error on overflow, while unchecked allows the value to wrap around.
using System; class Program { static void Main() { int max = int.MaxValue; try { int checkedResult = checked(max + 1); Console.WriteLine("Checked result: " + checkedResult); } catch (OverflowException) { Console.WriteLine("Overflow detected in checked block!"); } int uncheckedResult = unchecked(max + 1); Console.WriteLine("Unchecked result: " + uncheckedResult); } }
When to Use
Use checked when you want to catch errors caused by numbers going beyond their limits, such as in financial calculations or critical data processing where accuracy is important. It helps prevent bugs that can be hard to find by stopping the program when something goes wrong.
Use unchecked when performance is more important and you are sure overflow won't cause problems, like in low-level code or when working with bitwise operations where wrapping is expected.
Key Points
- checked throws an exception on overflow.
- unchecked ignores overflow and wraps values.
- Default overflow behavior depends on compiler settings.
- Use
checkedto catch errors early. - Use
uncheckedfor performance or intentional wrapping.
Key Takeaways
checked to detect and handle arithmetic overflow errors safely.unchecked to allow overflow without exceptions, enabling value wrapping.