bhylu.com

Advertisements

C# Checked Arithmetic

Use checked addition when overflow is a failure and reject negative booking changes before doing arithmetic.

How it works

C# supports checked and unchecked integral arithmetic contexts. Unchecked overflow can wrap, producing a representable but misleading count. A booking rule should not rely on wrapping. This helper accepts nonnegative counts, performs checked addition and returns null on rejection. The nullable result distinguishes a legitimate zero from failure. For capacity-limited updates, checking remaining space before mutation is often clearer than calculating an unrestricted total and trying to repair it afterwards.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;

internal static class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine($"Total: {AddCount(5, 4)}");
        Console.WriteLine($"Overflow rejected: {AddCount(int.MaxValue, 1) is null}");
    }

    internal static int? AddCount(int current, int extra)
    {
        if (current < 0 || extra < 0) return null;
        try { return checked(current + extra); }
        catch (OverflowException) { return null; }
    }
}

Expected result

Total: 9
Overflow rejected: True

Both arguments are checked for their domain before addition. Overflow becomes an explicit absent result rather than a wrapped successful-looking count. The caller does not assume a value when null is returned. Keep this failure policy visible in a method name, return type or documentation; silently swallowing every exception would conceal unrelated programming errors.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.