Letβs go through checked and unchecked arithmetic in C# β a way to control overflow behavior in numeric operations.
π 1. What is Overflow?
-
Overflow occurs when a calculation produces a value outside the range of the data type.
-
Example:
intranges from -2,147,483,648 to 2,147,483,647. Adding 1 toint.MaxValuecauses an overflow.
π 2. Unchecked Context (Default for C#)
-
By default, C# does not throw an exception on overflow for integer arithmetic.
-
The value wraps around.
int max = int.MaxValue; // 2147483647
int result = max + 1;
Console.WriteLine(result); // -2147483648 (wrap-around)- This is called unchecked arithmetic
π 3. Checked Context
-
Use
checkedto force an exception when overflow occurs -
Throws
System.OverflowException
int max = int.MaxValue;
try
{
int result = checked(max + 1);
}
catch (OverflowException ex)
{
Console.WriteLine("Overflow detected!"); // Output
}- You can also apply checked to a block:
checked
{
int a = int.MaxValue;
int b = a + 1; // Throws OverflowException
}π 4. Unchecked Keyword
- Explicitly ignore overflow even in a checked context
unchecked
{
int max = int.MaxValue;
int result = max + 1; // Wrap-around, no exception
Console.WriteLine(result); // -2147483648
}π 5. Use Cases
| Keyword | Behavior | Use Case |
|---|---|---|
unchecked | Overflow ignored, value wraps around | Performance-critical code where overflow is acceptable |
checked | Throws OverflowException on overflow | Safe arithmetic, financial calculations, critical systems |
π 6. Default Behavior
-
Integer literals and arithmetic are unchecked by default
-
Can enable checked-by-default in project settings (rarely used)
π 7. Summary Table
| Concept | Description |
|---|---|
| Overflow | When value exceeds the data typeβs range |
checked | Throws exception on overflow |
unchecked | Ignores overflow, wraps around |
| Default behavior | Arithmetic is unchecked unless specified |
β Tip:
-
Use
checkedfor critical calculations where incorrect results are dangerous -
Use
uncheckedfor performance or low-risk operations