TheAlgorithms/C-Sharp · error · ArgumentException

Array cannot be null or empty.

Error message

Array cannot be null or empty.

What it means

Kadane's algorithm needs at least one element because the maximum subarray is initialized from array[0]; a null or empty array has no valid answer, so FindMaximumSubarraySum(int[]) throws ArgumentException with parameter name 'array'.

Solutions

  1. Check array is non-null and Length > 0 before calling and decide the empty answer (0, NaN, or error) at the call site
  2. Fix upstream data loading so empty datasets are handled before analysis
  3. Catch ArgumentException and map it to an empty-input business rule

Example fix

// before
var max = KadanesAlgorithm.FindMaximumSubarraySum(values);
// after
var max = values is { Length: > 0 } ? KadanesAlgorithm.FindMaximumSubarraySum(values) : 0;
Defensive patterns

Strategy: validation

Validate before calling

if (array is null || array.Length == 0) return 0; // or your empty-input convention

Type guard

static bool IsNonEmpty(int[]? a) => a is { Length: > 0 };

Try / catch

try { return KadanesAlgorithm.FindMaximumSubarraySum(array); }
catch (ArgumentException ex) when (ex.ParamName == "array") { return 0; }

Prevention

When it happens

Trigger: Calling FindMaximumSubarraySum(null) or with an empty int[] from an empty dataset, empty file read, or a filter that removed all values.

Common situations: Aggregating profit/temperature series over an empty period; CSV/JSON inputs with no rows; unit tests passing empty arrays to check edge behavior.

Understand the failure class

Background: "must not be empty", "cannot be empty" — required-field validation errors across open-source libraries — this error's family across 41 libraries.

Related errors


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

Appendix: source

Thrown at Algorithms/Other/KadanesAlgorithm.cs:30

    ///     Finds the maximum sum of a contiguous subarray using Kadane's Algorithm.
    ///     The algorithm works by maintaining two variables:
    ///     - maxSoFar: The maximum sum found so far (global maximum)
    ///     - maxEndingHere: The maximum sum of subarray ending at current position (local maximum)
    ///     At each position, we decide whether to extend the existing subarray or start a new one.
    /// </summary>
    /// <param name="array">The input array of integers.</param>
    /// <returns>The maximum sum of a contiguous subarray.</returns>
    /// <exception cref="ArgumentException">Thrown when the input array is null or empty.</exception>
    /// <example>
    ///     Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4].
    ///     Output: 6 (subarray [4, -1, 2, 1]).
    /// </example>
    public static int FindMaximumSubarraySum(int[] array)
    {
        // Validate input to ensure array is not null or empty
        if (array == null || array.Length == 0)
        {
            throw new ArgumentException("Array cannot be null or empty.", nameof(array));
        }

        // Initialize both variables with the first element
        // maxSoFar tracks the best sum we've seen across all subarrays
        int maxSoFar = array[0];

        // maxEndingHere tracks the best sum ending at the current position
        int maxEndingHere = array[0];

        // Iterate through the array starting from the second element
        for (int i = 1; i < array.Length; i++)
        {
            // Key decision: Either extend the current subarray or start fresh
            // If adding current element to existing sum is worse than the element alone,
            // it's better to start a new subarray from current element
            maxEndingHere = Math.Max(array[i], maxEndingHere + array[i]);

            // Update the global maximum if current subarray sum is better

View on GitHub (pinned to 96e2905cab)