Phase 2 of 30 · Topic 2.5

Unchecked Arithmetic, Overflow Exceptions & Native Sized Integers (nint)

1Concept

By default, C# integer arithmetic is `unchecked` (wraps on overflow for speed). The `checked` block enforces hardware-level overflow checking via `OverflowException`. C# 9+ introduces `nint` and `nuint` mapped directly to native CPU register widths.

2Architecture Diagram

int.MaxValue (2,147,483,647) + 1:
├── Unchecked (Default) ──> Wraps to -2,147,483,648 (Binary two's complement overflow)
└── Checked Context     ──> Throws System.OverflowException (Safe Enterprise Mode)

3Code Example

C# 13 & .NET 9
using System;

public class ArithmeticOverflowDemo
{
    public static void Main()
    {
        int max = int.MaxValue;

        // Unchecked: wraps around silently
        int wrapped = unchecked(max + 1);
        Console.WriteLine($"Unchecked: {wrapped}");

        // Checked: throws OverflowException
        try
        {
            int safe = checked(max + 1);
        }
        catch (OverflowException)
        {
            Console.WriteLine("Checked context successfully caught integer overflow!");
        }

        // Native integer (64-bit on 64-bit OS)
        nint nativeInt = IntPtr.Size == 8 ? 100_000_000_000L : 100;
        Console.WriteLine($"Native integer size: {IntPtr.Size * 8}-bit, Value: {nativeInt}");
    }
}

4Expected Output

Unchecked: -2147483648
Checked context successfully caught integer overflow!
Native integer size: 64-bit, Value: 100000000000

5Key Takeaways

  • Financial and cryptography calculations must always execute inside `checked` blocks.
  • `nint` is optimized for high-performance array indexing and pointer offsets.
  • Use `Math.BigMul` in .NET 9 to compute 64-bit x 64-bit products without overflow.