TheAlgorithms/C-Sharp · error · ArgumentException

Input must be a non-negative integer.

Error message

Input must be a non-negative integer.

What it means

SumOfDigits.Calculate computes digit sums only for non-negative integers; digit extraction from a negative number would never terminate or would be ill-defined for this implementation, so it throws ArgumentException with the parameter name when number < 0.

Solutions

  1. Validate the number is >= 0 before calling, or use Math.Abs when sign is irrelevant
  2. Fix upstream logic that lets values go negative when they should not
  3. Catch ArgumentException and map it to a user-facing 'value must be non-negative' message

Example fix

// before
var sum = SumOfDigits.Calculate(userValue); // may be negative
// after
if (userValue < 0) throw new FormatException("digits expected");
var sum = SumOfDigits.Calculate(userValue);
Defensive patterns

Strategy: validation

Validate before calling

if (number < 0) throw new ArgumentOutOfRangeException(nameof(number));

Type guard

static bool IsNonNegative(int n) => n >= 0;

Try / catch

try { return SumOfDigits.Calculate(number); }
catch (ArgumentException ex) when (ex.ParamName == "number") { /* handle negative input */ }

Prevention

When it happens

Trigger: Calling Calculate(-5) or Calculate on a value that became negative through subtraction, overflow, or unvalidated user input.

Common situations: Processing signed user input such as temperatures or account deltas; int.MinValue arithmetic that wrapped negative; passing unchecked form/console input.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/fd22bf84e568d154. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Numeric/SumOfDigits.cs:22

/// <summary>
///     Provides functionality to calculate the sum of the digits of an integer.
/// </summary>
public static class SumOfDigits
{
    /// <summary>
    ///     Calculates the sum of the digits of a non-negative integer.
    ///     The method iteratively uses the modulus operator (%) to get the last digit
    ///     and the division operator (/) to drop the last digit until the number is 0.
    /// </summary>
    /// <param name="number">The non-negative integer whose digits are to be summed.</param>
    /// <returns>The sum of the digits of the input number.</returns>
    /// <exception cref="ArgumentException">Thrown if the input number is negative.</exception>
    public static int Calculate(int number)
    {
        if (number < 0)
        {
            throw new ArgumentException("Input must be a non-negative integer.", nameof(number));
        }

        if (number == 0)
        {
            return 0;
        }

        int sum = 0;
        int currentNumber = number;

        // Loop until the number becomes 0
        while (currentNumber > 0)
        {
            // Get the last digit (e.g., 123 % 10 = 3)
            int digit = currentNumber % 10;

            // Add the digit to the sum
            sum += digit;

View on GitHub (pinned to 96e2905cab)