C# / Basic: Typed Programs and Object Contracts / Lesson 7
Checked integer arithmetic
Detect C# integral overflow with checked expressions and tests.
On this page
Lesson goals
- Choose a checked overflow policy.
- Test arithmetic boundaries.
- Trace checked arithmetic and narrowing at their actual expression sites.
- Design boundary tests and preserve state on rejected overflow.
Choose an overflow policy
Integer types have finite ranges, so a mathematical result may not fit even when both operands are valid. An overflow-checking context determines the behavior of affected integral operations. Choose a policy from the domain: reject an invalid result or deliberately use wrapping behavior where specified. Document that choice and test the boundary rather than relying only on small values.
Use checked arithmetic
A checked expression throws OverflowException when an affected integer operation exceeds its range. The first example adds two fixed integers and prints a valid result. Handle overflow at a boundary that can report or recover from it; do not silently substitute an ordinary total. Check every intermediate operation that may overflow, not only a later assignment to a wider type.
using System;
public class Program
{
public static void Main()
{
int a = 20;
int b = 22;
Console.WriteLine(checked(a + b));
}
}
42
The sum fits in int.
Understand the checked scope
The second example deliberately adds one to int.MaxValue inside checked and handles the exception. An unchecked context can provide wrapping behavior for applicable integral operations, but that behavior should be intentional. Checking is textual: placing a method call in a checked block does not automatically change the overflow context inside the called method. Review where the arithmetic actually occurs.
using System;
public class Program
{
public static void Main()
{
int value = int.MaxValue;
try
{
Console.WriteLine(checked(value + 1));
}
catch (OverflowException)
{
Console.WriteLine("overflow");
}
}
}
overflow
The mathematical sum exceeds the int range.
Review conversions
A wider destination cannot recover a result that already overflowed in a narrower expression. Choose the operand types before arithmetic and verify that the wider range meets the domain requirement. A narrowing conversion can lose information; use a checked conversion when rejection is required. Keep units explicit when the result represents bytes, counts, or time.
Test numeric boundaries
Test zero, an ordinary result, the largest valid result, and the first overflow. Assert the value or the expected exception separately. If the calculation controls an allocation, enforce both arithmetic safety and a practical application limit. Repeat the original failing operation and confirm that the caller receives the documented failure rather than a misleading wrapped result.
Start from the numeric domain
A mathematical integer has no fixed upper bound, but a C# integral type has a finite representable interval. For int that interval runs from -2147483648 through 2147483647. Valid operands can therefore produce an invalid result: int.MaxValue and 1 each fit, while their mathematical sum does not. State the application policy before implementing arithmetic. A billing total might reject an unrepresentable result; an algorithm intentionally modeling fixed-width modular arithmetic may instead specify wrapping for the relevant operations. Neither behavior automatically supplies a business limit, such as a maximum permitted order size. Include units, valid operand ranges, allowed result range and failure behavior in the contract. This lesson discusses built-in integral operations and conversions under the C# 14 and net10.0 course baseline; it does not assume an SDK is present on the learner’s machine.
Place checking at the operation
A checked expression or statement selects overflow checking for applicable integral operations and conversions written within its textual scope. With nonconstant operands, an overflowing checked operation throws OverflowException instead of producing its wrapped result. An explicitly unchecked context gives wrapping behavior for applicable built-in integral arithmetic and conversions. Constant expressions have separate compile-time rules, so use variables when demonstrating a runtime exception rather than claiming an overflowing checked constant will run. Project settings can affect the default context for nonconstant expressions; make the policy explicit where it matters. The scope is lexical, not a dynamic setting inherited by another method body. A checked block containing a call does not by itself check an addition written inside the called method. Put the intended policy at the arithmetic site and document it for callers.
Trace types before assignment
Determine the type of every operand and intermediate expression before looking at the destination. When two int variables are multiplied, their product is computed as int even if the assignment target is long. In a checked context an unrepresentable product throws before assignment; in an explicitly unchecked context an already wrapped int can be widened but its lost information is not restored. Convert one operand to long before multiplication if long covers the full required product. Then check long’s own limits and the domain limit rather than treating widening as unlimited safety. Small integral types such as byte are promoted in ordinary arithmetic, so two byte operands generally produce an int result. A later explicit conversion back to byte is a separate narrowing operation and can itself overflow in a checked context. Trace the operation and conversion independently.
Prove guards and preserve state
A guard can reject an operation before it is evaluated, but its own arithmetic must be safe under the stated preconditions. For nonnegative int operands a and b, b is at most int.MaxValue, so int.MaxValue - b is representable; reject a greater than that remaining capacity before adding. This one-sided proof does not cover arbitrary signed operands. A checked expression is another approach when an exception fits the API contract. Compute into a temporary and commit state only after successful calculation if failure must leave the old value unchanged. For narrowing, check the target range first or use an explicit checked conversion and handle its failure. Distinguish parsing from arithmetic: a string may fail to parse before any addition takes place, and a parsed number can still violate a business limit.
Test the edge and the policy
Tests should include ordinary positive and negative cases, zero, exact representable endpoints and the first result beyond each applicable limit. Assert successful values separately from OverflowException and verify that state remains unchanged when rejection is promised. For multiplication, choose operands whose individual values fit but whose intermediate product does not, and compare widening before versus after the operation. Test the called method’s overflow behavior independently from its caller’s context. For a size calculation, a result fitting in long is not sufficient permission to allocate: reject values exceeding the practical application limit before attempting allocation. Keep examples deterministic and avoid relying on an exception’s localized message. Snippets below are illustrative fragments, not executed in a local SDK; the stated results follow the documented language rules and still require qualification in the target project.
20 worked examples
1. Exact upper boundary
Problem: What value is produced just at the upper int boundary?
- The mathematical sum equals int.MaxValue exactly.
- That endpoint is representable, so the checked addition succeeds.
int a = int.MaxValue - 2;
int b = 2;
int result = checked(a + b);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: result is 2147483647.
Why this result follows: Checked arithmetic rejects overflow, not an in-range boundary value.
2. Checked lower addition
Problem: What happens when this negative sum falls below int.MinValue?
- Both operands are representable int values.
- Their mathematical sum is below the minimum, so checked addition throws.
int a = int.MinValue;
int b = -1;
int result = checked(a + b);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: OverflowException is thrown before result is assigned.
Why this result follows: The lower bound is part of the overflow contract as well as the upper bound.
3. Subtract at the upper edge
Problem: Does subtracting a negative value fit here?
- Subtracting -1 mathematically adds one to int.MaxValue.
- The result exceeds the int maximum and checked subtraction throws.
int a = int.MaxValue;
int b = -1;
int difference = checked(a - b);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: The subtraction throws OverflowException.
Why this result follows: Subtraction can overflow even when both inputs individually fit.
4. Checked multiplication
Problem: What happens to this int intermediate product?
- Each operand is a valid int but their product is 2500000000.
- That product exceeds int.MaxValue, so the checked multiplication throws.
int width = 50000;
int height = 50000;
int area = checked(width * height);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: OverflowException occurs before area is assigned.
Why this result follows: The intermediate operation uses the operands’ int type.
5. Widen before multiplication
Problem: What does widening one operand do to this product?
- The cast changes the multiplication to long arithmetic.
- The product 2500000000 fits in long, so the expression succeeds.
int width = 50000;
int height = 50000;
long area = checked((long)width * height);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: area is 2500000000.
Why this result follows: Widening an operand changes the intermediate operation’s range.
6. Widen after wrapping
Problem: What reaches long after explicitly unchecked int multiplication?
- The int multiplication wraps 2500000000 to -1794967296.
- Assignment then widens that already wrapped int to long.
int width = 50000;
int height = 50000;
long area = unchecked(width * height);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: area is -1794967296, not the mathematical product.
Why this result follows: A wider destination cannot reconstruct bits lost by the earlier operation.
7. Unchecked upper wrap
Problem: What is the result of this deliberate unchecked increment?
- The mathematical result is one beyond the maximum signed int.
- The explicitly unchecked built-in int addition wraps to int.MinValue.
int x = int.MaxValue;
int y = unchecked(x + 1);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: y is -2147483648.
Why this result follows: Unchecked integral arithmetic discards overflowing high bits for this operation.
8. Unchecked lower wrap
Problem: What is the result when one is subtracted from int.MinValue?
- The mathematical result is one below the minimum signed int.
- Unchecked subtraction wraps the retained bits to int.MaxValue.
int x = int.MinValue;
int y = unchecked(x - 1);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: y is 2147483647.
Why this result follows: The explicit unchecked context selects wrapping for this built-in subtraction.
9. Checked narrowing succeeds
Problem: Can this int be converted to byte without loss?
- The target byte range is 0 through 255.
- The input lies at its upper boundary, so the checked conversion succeeds.
int input = 255;
byte result = checked((byte)input);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: result is byte value 255.
Why this result follows: The conversion fits exactly within the destination range.
10. Checked narrowing fails
Problem: What happens when converting negative one to byte?
- A byte cannot represent a negative value.
- The checked explicit conversion detects the out-of-range input and throws.
int input = -1;
byte result = checked((byte)input);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: OverflowException is thrown before assignment.
Why this result follows: Checked narrowing rejects a value outside the target interval.
11. Unchecked narrowing
Problem: What byte value results from explicitly unchecked conversion of 256?
- The value 256 needs more than the eight bits retained by byte.
- The explicit unchecked conversion retains the low eight bits, all zero here.
int input = 256;
byte result = unchecked((byte)input);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: result is 0.
Why this result follows: An unchecked narrowing conversion may discard information.
12. Byte arithmetic promotion
Problem: What type and value does the sum have before narrowing?
- The operands are promoted for the built-in arithmetic operation.
- The int sum 300 is representable even though 300 is outside byte range.
byte a = 200, b = 100;
int sum = a + b;
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: sum is int value 300.
Why this result follows: Small integral operands are promoted for this addition.
13. Separate arithmetic and conversion
Problem: Which operation fails in this checked expression?
- The promoted int addition succeeds with 300.
- The subsequent checked conversion to byte fails because 300 exceeds 255.
byte a = 200, b = 100;
byte result = checked((byte)(a + b));
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: OverflowException arises at the narrowing conversion.
Why this result follows: Checking the conversion is distinct from checking the promoted addition.
14. Lexical method scope
Problem: Does the caller’s checked block change this method’s explicit policy?
- The addition is written inside Add, where it is explicitly unchecked.
- The checked caller does not change the called method body, so the addition wraps.
static int Add(int a, int b) => unchecked(a + b);
int x = int.MaxValue;
int result;
checked { result = Add(x, 1); }
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: result is int.MinValue.
Why this result follows: Overflow context is applied at the operation’s textual location.
15. Checked method called outside
Problem: What happens when this method checks its own addition?
- The called method explicitly places its addition in checked.
- The sum is outside int range, so the method throws before returning.
static int Add(int a, int b) => checked(a + b);
int x = int.MaxValue;
int result = Add(x, 1);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: The call throws OverflowException.
Why this result follows: The operation’s own checked context governs the addition.
16. Constant-expression overflow
Problem: Why does this declaration fail before runtime?
- The operands form a constant expression whose mathematical result exceeds int range.
- A checked constant overflow is a compile-time error rather than a runtime exception.
const int result = checked(int.MaxValue + 1);
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: The compiler rejects the constant declaration.
Why this result follows: Constant expressions are evaluated under compile-time overflow rules.
17. Guard a nonnegative sum
Problem: Does this input fit the remaining int capacity?
- The nonnegative b leaves capacity int.MaxValue - 4.
- a is one greater than that limit, so the guard rejects addition.
int a = int.MaxValue - 3;
int b = 4;
bool fits = a <= int.MaxValue - b;
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: fits is false; the addition should not be performed under this policy.
Why this result follows: The guard compares against safely calculated remaining capacity.
18. Preserve old state
Problem: What value remains after the checked assignment fails?
- The right side throws before the assignment can occur.
- The catch does not alter total, so it retains its previous value.
int total = int.MaxValue;
try { total = checked(total + 1); }
catch (OverflowException) { }
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: total remains int.MaxValue.
Why this result follows: Assignment commits only after its right-hand expression succeeds.
19. Earlier mutation persists
Problem: What remains after a later checked operation throws?
- count is incremented to 2 before the overflowing addition.
- The failed assignment leaves total unchanged, but the earlier increment is not rolled back.
int count = 1;
int total = int.MaxValue;
try { count++; total = checked(total + 1); }
catch (OverflowException) { }
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: count is 2 and total remains int.MaxValue.
Why this result follows: An exception does not automatically undo preceding state changes.
20. Practical allocation bound
Problem: Can this representable size pass the application’s stated limit?
- The checked long multiplication produces 8000000 without overflow.
- That value exceeds the application limit of 4000000 bytes.
long items = 1000000;
long bytes = checked(items * 8L);
long limit = 4000000;
bool allowed = bytes <= limit;
Illustrative fragment, not executed locally; assumes a suitable C# project context.
Expected result: bytes is 8000000 and allowed is false; no allocation is attempted.
Why this result follows: Representability and permission to allocate are distinct checks.
Common errors and fixes
A total wraps unexpectedly
- Why it happens
- An operation exceeded its range in an unchecked context.
- How to fix it
- Use checked where rejection is required.
- Prevent it next time
- Test numeric boundaries.
A wider result is already wrong
- Why it happens
- A narrower intermediate operation overflowed.
- How to fix it
- Choose operand types before arithmetic.
- Prevent it next time
- Review intermediate expressions.
A called method still wraps
- Why it happens
- The outer checked block does not change the method body’s context.
- How to fix it
- Check arithmetic within that method.
- Prevent it next time
- Document overflow behavior at each boundary.
20 practice exercises
1. What does checked(20 + 22) produce?
Show hint
Calculate the sum and compare it with int range.
Show worked solution
It produces 42 because the sum fits in int.
Both constants are int and their sum is 42, well within the int interval. The checked constant expression is valid and evaluates to 42; no overflow exception occurs.
Check your solution
- The mathematical sum is 42.
- 42 lies within int range and is returned.
2. Why can a wider destination still receive a wrong value?
Show hint
Find the type of the expression before the assignment.
Show worked solution
A narrower intermediate expression can overflow before assignment. Select the required type before the operation.
If int operands produce an int intermediate, overflow can occur before assignment to long. Widen an operand before the operation, then check that the long result and application domain can contain the intended value.
Check your solution
- The analysis identifies the narrower intermediate operation.
- The repair widens an operand before arithmetic and checks the required range.
3. A nonnegative counter is at int.MaxValue - 1 and receives two increments. Describe each checked result and state.
Show hint
The first update reaches the endpoint; the next exceeds it.
Show worked solution
The first checked increment succeeds and stores int.MaxValue. The second throws OverflowException before assignment, leaving the counter at int.MaxValue if the operation has no earlier mutation.
Check your solution
- The first increment reaches int.MaxValue.
- The second fails without changing that value.
4. Design a checked decrement test for a value at int.MinValue and another just above it.
Show hint
Compare each mathematical result with the lower endpoint.
Show worked solution
At int.MinValue + 1, subtracting one succeeds with int.MinValue. At int.MinValue, subtracting one throws OverflowException before assignment; assert the old state separately on failure.
Check your solution
- The adjacent valid decrement returns int.MinValue.
- The first out-of-range decrement throws and preserves the assigned variable.
5. A checked subtraction computes int.MinValue - 1. Explain why the operands can both be valid while the result fails.
Show hint
Representability of operands does not imply representability of their result.
Show worked solution
Both int.MinValue and 1 are in the int range, but the mathematical difference is one below its minimum. Checked subtraction throws OverflowException rather than returning an ordinary int value.
Check your solution
- Both operands are valid int values.
- The checked result throws OverflowException.
6. A report multiplies int dimensions 70000 and 70000 then casts the product to long. Diagnose and repair the calculation.
Show hint
Widen an operand before the multiplication.
Show worked solution
The int product exceeds int.MaxValue before the cast; checked arithmetic throws and unchecked arithmetic can wrap. Use checked((long)width * height), yielding 4900000000, and verify any domain limit separately.
Check your solution
- The original intermediate is int and cannot represent 4900000000.
- The widened operation returns 4900000000 as long.
7. A device protocol deliberately wraps an int sequence number. Specify the policy and predict int.MaxValue plus one.
Show hint
Use an explicit unchecked operation for the intended modular behavior.
Show worked solution
Document fixed-width wrapping and compute unchecked(sequence + 1). For int.MaxValue the result is int.MinValue; test that transition and distinguish this protocol rule from business totals that must reject overflow.
Check your solution
- The boundary transition produces int.MinValue.
- The contract explicitly requires wrapping.
8. An integer 256 must become a byte only if no information is lost. Design validation and failure.
Show hint
Check the target range or use a checked conversion.
Show worked solution
Reject values outside 0 through 255 before casting, or perform a checked conversion and handle OverflowException. The input 256 is rejected; 255 succeeds and preserves its value.
Check your solution
- 256 is rejected.
- 255 converts to byte value 255.
9. Two byte counts 180 and 90 are added and the result is assigned to byte. Identify both operation types and a safe policy.
Show hint
The addition is promoted before the narrowing conversion.
Show worked solution
The addition produces int 270, which fits int but not byte. Keep the int result if the domain allows it, or reject the checked byte conversion; do not treat promotion as permission to narrow without loss.
Check your solution
- The intermediate int sum is 270.
- Checked conversion to byte rejects 270.
10. A checked block calls a helper whose addition is explicitly unchecked. The input is int.MaxValue and 1. Explain the observed policy.
Show hint
Locate the arithmetic in the helper body.
Show worked solution
The checked caller does not change the helper’s lexical context; its explicit unchecked addition wraps to int.MinValue. Put checked in the helper when its own contract requires overflow rejection.
Check your solution
- The existing helper produces int.MinValue.
- A checked helper throws for the same operands.
11. A developer uses checked(int.MaxValue + 1) as a runtime test but the compiler rejects it. Explain how to test runtime behavior.
Show hint
Distinguish constant evaluation from nonconstant evaluation.
Show worked solution
The checked constant expression overflows at compile time. Store int.MaxValue in a nonconstant local, evaluate checked(value + 1), and assert OverflowException at runtime in the qualified target environment.
Check your solution
- The constant form is a compile-time error.
- The nonconstant checked operation is tested for OverflowException.
12. A nonnegative addition guard uses a <= int.MaxValue - b. State the assumptions and evaluate a=int.MaxValue-5, b=5.
Show hint
The subtraction must itself be representable.
Show worked solution
Require both inputs to be nonnegative int values. Then int.MaxValue - b is representable, and a equals the remaining capacity, so addition succeeds exactly at int.MaxValue. The proof does not cover arbitrary signed inputs.
Check your solution
- The equality case is accepted.
- The stated proof requires nonnegative inputs.
13. A total must remain unchanged on overflow, but a method increments a separate count first. Redesign the transition.
Show hint
Compute and validate all new state before committing it.
Show worked solution
Compute the checked total and any checked count in temporary variables, then assign both only after all calculations succeed. If either fails, report rejection with both old values retained under the documented synchronization policy.
Check your solution
- Overflow leaves both original fields unchanged.
- A successful update commits both computed values.
14. A long byte count fits the type but exceeds a 2,000,000-byte application limit. Design the allocation gate.
Show hint
Arithmetic safety and resource policy are separate.
Show worked solution
Calculate the required bytes with checked long arithmetic and reject negative or greater-than-limit results before allocating. A representable 2,000,001 is rejected by policy even though no numeric overflow occurred.
Check your solution
- 2,000,001 is rejected without allocation.
- An allowed in-range size is tested separately.
15. A loop sums nonnegative int readings and must reject overflow without losing the previous valid sum. Design its update.
Show hint
Evaluate the checked expression before replacing the accumulator.
Show worked solution
Compute checked(total + reading) into a temporary and assign only on success. On overflow stop and report the failing position while retaining the last valid total; also validate that each reading satisfies the domain.
Check your solution
- An overflow leaves the last valid total intact.
- The reported position identifies the rejected reading.
16. A calculation checks the final addition but an earlier int multiplication can wrap. Explain the defect and repair.
Show hint
Trace each intermediate operation in order.
Show worked solution
Checking only the final addition does not retroactively check a product already computed elsewhere. Widen or check the multiplication at its own site, then check the addition and validate the full domain.
Check your solution
- The multiplication site has an explicit overflow policy.
- A test uses operands whose product exceeds int range.
17. A nullable text input is parsed and then added to a stored int. Define distinct parse and overflow failures.
Show hint
No addition should occur when parsing fails.
Show worked solution
Use TryParse and return an invalid-input result on failure; only then perform checked addition and report overflow separately. Do not update the stored total unless both stages succeed.
Check your solution
- Invalid text causes no addition or state update.
- A parsed value that overflows reports a distinct failure.
18. Design boundary tests for checked conversion from int to sbyte.
Show hint
Include both valid endpoints and the first value outside each.
Show worked solution
Test -128 and 127 as successful conversions, and -129 and 128 as OverflowException cases. Include zero as an ordinary value and assert that no target assignment occurs on a thrown conversion.
Check your solution
- -128 and 127 convert successfully.
- -129 and 128 throw OverflowException.
19. An API catches OverflowException and returns zero, although zero is a valid computed total. Redesign its result.
Show hint
Keep the success signal separate from the value.
Show worked solution
Return a Try-style Boolean with an output value, a documented result type, or propagate the documented exception. A successful zero must be distinguishable from rejected overflow and failure must not silently modify state.
Check your solution
- A valid zero reports success.
- Overflow reports failure without being mistaken for zero.
20. A calculation changes from int to long operands. Why are boundary and policy tests still needed?
Show hint
Long is wider but finite.
Show worked solution
Long increases the representable range but can still overflow and may exceed an application limit long before its numeric boundary. Test the expected maximum, the first rejected business value and long overflow where relevant.
Check your solution
- The business limit is checked independently of numeric range.
- A long overflow case has an explicit documented result.
Key takeaways
- Choose overflow behavior explicitly.
- Check intermediate expressions and conversions.
- Operand types determine intermediate arithmetic before assignment.
- Checked scope is textual and exceptions do not undo prior mutations.
- Representability and practical domain limits are separate checks.