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: int ranges from -2,147,483,648 to 2,147,483,647. Adding 1 to int.MaxValue causes 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 checked to 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

KeywordBehaviorUse Case
uncheckedOverflow ignored, value wraps aroundPerformance-critical code where overflow is acceptable
checkedThrows OverflowException on overflowSafe 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

ConceptDescription
OverflowWhen value exceeds the data type’s range
checkedThrows exception on overflow
uncheckedIgnores overflow, wraps around
Default behaviorArithmetic is unchecked unless specified

βœ… Tip:

  • Use checked for critical calculations where incorrect results are dangerous

  • Use unchecked for performance or low-risk operations